我有一个带有示例数据的input
data.frame
input <- structure(list(NAME = structure(c(3L, 7L, 6L, 4L, 2L, 5L, 1L), .Label = c("Example2","Example7", "Test", "Test2", "Test3", "Test6", "Test77"), class = "factor"), REFERENCE = structure(c(2L, 3L, 1L, 1L, 4L, 2L, 1L), .Label = c("EXAMPLE5", "REGION1", "REGION2", "REGION77"), class = "factor"), VALUE = structure(c(1L,2L, 3L, 4L, 6L, 5L, 7L), .Label = c("120", "13", "14", "65", "89", "B", "C"), class = "factor")), .Names = c("NAME", "REFERENCE", "VALUE"), class = "data.frame", row.names = c(NA, -7L))
NAME REFERENCE VALUE
1 Test REGION1 120
2 Test77 REGION2 13
3 Test6 EXAMPLE5 14
4 Test2 EXAMPLE5 65
5 Example7 REGION77 B
6 Test3 REGION1 89
7 Example2 EXAMPLE5 C
我有第二个data.frame filelist
,其中数据的排序方式如此。
filelist <- structure(list(NAME = structure(c(3L, 5L, 1L, 6L, 4L, 2L), .Label = c("","Example2", "Test", "Test2", "Test3", "Test6"), class = "factor"), REFERENCE = structure(c(3L, 3L, 1L, 2L, 2L, 2L), .Label = c("", "EXAMPLE5", "REGION1"), class = "factor")), .Names = c("NAME","REFERENCE"), class = "data.frame", row.names = c(NA, -6L))
NAME REFERENCE
1 Test REGION1
2 Test3 REGION1
3
4 Test6 EXAMPLE5
5 Test2 EXAMPLE5
6 Example2 EXAMPLE5
filelist
包含应写入按REFERENCE
列分组的单独data.frames中的所有值(如下面的代码所示)。
到目前为止,我通过使用下面的代码并手动对列进行子集化然后将它们组合在一起来实现。有没有办法可以独立完成?
# Manual selection REGION1
Test <- subset(input, NAME=="Test")
Test3 <- subset(input, NAME=="Test3")
# rbind them together
REGION1 <- rbind(Test, Test3)
# Manual selection EXAMPLE5
Test6 <- subset(input, NAME=="Test6")
Test2 <- subset(input, NAME=="Test2")
Example2 <- subset(input, NAME=="Example2")
# rbind them together
EXAMPLE5 <- rbind(Test6, Test2,Example2)
答案 0 :(得分:2)
这可能会有所帮助,你会追求什么。您似乎想要合并输入和文件列表。然后,您想为每个REFERENCE级别创建一个数据框。
library(dplyr)
ana <- filelist %>%
left_join(., input)
split(ana, f = ana$REFERENCE )
#[[1]]
# NAME REFERENCE VALUE
#3 <NA>
#$EXAMPLE5
# NAME REFERENCE VALUE
#4 Test6 EXAMPLE5 14
#5 Test2 EXAMPLE5 65
#6 Example2 EXAMPLE5 C
#$REGION1
# NAME REFERENCE VALUE
#1 Test REGION1 120
#2 Test3 REGION1 89
修改强>
非常感谢@Richard Scriven。这是OP想要的最后一步。
list2env(split(ana, f = ana$REFERENCE )[-1], .GlobalEnv)
#> EXAMPLE5
# NAME REFERENCE VALUE
#4 Test6 EXAMPLE5 14
#5 Test2 EXAMPLE5 65
#6 Example2 EXAMPLE5 C