我想绑定两个数据文件的列。根据第一个dataframe中单元格的值,应该在我的环境中的几个数据文件中选择第二个dataframe。
样本数据
test <- structure(list(main_activity = structure(c(1L, 9L), .Label = c("Manufacturing",
"Manufacturing; Retail", "Manufacturing; Services", "Manufacturing; Wholesale",
"Manufacturing; Wholesale; Services", "Retail", "Retail; Services",
"Retail; Wholesale", "Services", "Services; Manufacturing", "Services; Retail",
"Services; Wholesale", "Wholesale", "Wholesale; Manufacturing",
"Wholesale; Retail", "Wholesale; Services"), class = "factor"),
p_l_for_period_net_income_th_eur_2019 = c(-4849.968, -4416.404
), Name = c("A", "B")), class = "data.frame", row.names = c(NA,
-2L))
Manufacturing_2015 <- as.data.frame(matrix(data = c(2000)))
Services_2015 <- as.data.frame(matrix(data = c(3000)))我想要做的是检查列'main_activity‘的值,并将与该名称匹配的dataframe与'test’数据name绑定。因此,我们的目标是实现以下目标:
期望结果
binded_A <- cbind(test %>% filter(Name == "A"), Manufacturing_2015)
binded_B <- cbind(test %>% filter(Name == "B"), Services_2015)有办法自动完成吗?
发布于 2020-06-01 00:11:23
您可以使用ls从全局环境中根据其在main_activity中的值选择数据帧,并将数据转换为原始数据子集。
result <- lapply(test$main_activity, function(x) cbind(subset(test,
main_activity == x), get(ls(pattern = x, envir = .GlobalEnv))))
result
#[[1]]
# main_activity p_l_for_period_net_income_th_eur_2019 Name V1
#1 Manufacturing -4849.968 A 2000
#[[2]]
# main_activity p_l_for_period_net_income_th_eur_2019 Name V1
#2 Services -4416.404 B 3000这将返回一个数据文件列表,如果您需要它们作为单独的dataframes命名并使用list2env。
names(result) <- paste0('binded_', test$Name)
list2env(result, .GlobalEnv)https://stackoverflow.com/questions/62123892
复制相似问题