我有一个数据框架,上面有作物名称和它们各自的联合国粮食及农业组织代码。不幸的是,一些作物类别,如“其他谷物”,有多个联合国粮食组织代码,多个范围的联合国粮食组织代码,甚至更糟--多个范围的联合国粮食组织代码。
具有不同格式的数据框架的数据片段。
> FAOCODE_crops
SPAM_full_name FAOCODE
1 wheat 15
2 rice 27
8 other cereals 68,71,75,89,92,94,97,101,103,108
27 other oil crops 260:310,312:339
31 other fibre crops 773:821使用下面的代码成功地分解了这些数字,
unlist(lapply(unlist(strsplit(FAOCODE_crops$FAOCODE, ",")), function(x) eval(parse(text = x))))
[1] 15 27 56 44 79 79 83 68 71 75 89 92 94 97 101 103 108..。但我无法将这些数字合并回dataframe中,因为在dataframe中,每个FAOCODE都有自己的行。
> FAOCODE_crops$FAOCODE <- unlist(lapply(unlist(strsplit(MAPSPAM_crops$FAOCODE, ",")), function(x) eval(parse(text = x))))
Error in `$<-.data.frame`(`*tmp*`, FAOCODE, value = c(15, 27, 56, 44, :
replacement has 571 rows, data has 42我完全理解为什么它不能成功合并,但我不能想出一种方法来为每个FAOCODE填充一个新行,如下所示:
SPAM_full_name FAOCODE
1 wheat 15
2 rice 27
8 other cereals 68
8 other cereals 71
8 other cereals 75
8 other cereals 89以此类推。
任何帮助都是非常感谢的!
发布于 2020-02-25 10:48:42
我们可以使用separate_rows来分隔,。之后,我们可以使用map和~eval(parse(text = .x))遍历FAOCODE来计算数字范围。最后,我们可以使用unnest对数据框架进行扩展。
library(tidyverse)
dat2 <- dat %>%
separate_rows(FAOCODE, sep = ",") %>%
mutate(FAOCODE = map(FAOCODE, ~eval(parse(text = .x)))) %>%
unnest(cols = FAOCODE)
dat2
# # A tibble: 140 x 2
# SPAM_full_name FAOCODE
# <chr> <dbl>
# 1 wheat 15
# 2 rice 27
# 3 other cereals 68
# 4 other cereals 71
# 5 other cereals 75
# 6 other cereals 89
# 7 other cereals 92
# 8 other cereals 94
# 9 other cereals 97
# 10 other cereals 101
# # ... with 130 more rowsDATA
dat <- read.table(text = " SPAM_full_name FAOCODE
1 wheat 15
2 rice 27
8 'other cereals' '68,71,75,89,92,94,97,101,103,108'
27 'other oil crops' '260:310,312:339'
31 'other fibre crops' '773:821'",
header = TRUE, stringsAsFactors = FALSE)https://stackoverflow.com/questions/60381897
复制相似问题