有没有办法根据列表中项目的名称在 R 中合并数据框和列表?
想要合并这个的示例:
还有这个:
进入如下所示的数据框:
数据框示例
data = structure(list(Col.A = c("x", "x", "x", "x", "x", "x", "x", "x",
"x", "x", "x", "x", "x", "x", "x"), Col.B = c("x", "x", "x",
"x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x"),
Group = c("Group1", "Group1", "Group1", "Group1", "Group1",
"Group2", "Group2", "Group2", "Group2", "Group2", "Group3",
"Group3", "Group3", "Group3", "Group3"), Variable = c("V1",
"V2", "V3", "V4", "V5", "V1", "V2", "V3", "V4", "V5", "V1",
"V2", "V3", "V4", "V5")), class = "data.frame", row.names = c(NA,
-15L))
示例列表:
List = list(GROUP1 = list(V1 = 0.857138, V2 = 1, V3 = 0.5,
V4 = "not limiting", V5 = 0.1),
Group2 = list(V1 = 0.65, V2 = 1, V3 = 1,
V4 = 0.6, V5 = 0.25),
Group3 = list(V1 = 0.65, V2 = 0.75, V3 = 0.3,
V4 = 1, V5 = 1))
一个 tidyverse 解决方案:
library(dplyr)
library(tidyr)
library(tibble)
names(List) <- stringr::str_to_sentence(names(List))
List |>
unlist() |>
enframe() |>
separate_wider_delim(cols = name, names = c("Group", "Variable"), delim = ".") |>
right_join(data)
Group Variable value Col.A Col.B
<chr> <chr> <chr> <chr> <chr>
1 Group1 V1 0.857138 x x
2 Group1 V2 1 x x
3 Group1 V3 0.5 x x
4 Group1 V4 not limiting x x
5 Group1 V5 0.1 x x
6 Group2 V1 0.65 x x
7 Group2 V2 1 x x
8 Group2 V3 1 x x
9 Group2 V4 0.6 x x
10 Group2 V5 0.25 x x
11 Group3 V1 0.65 x x
12 Group3 V2 0.75 x x
13 Group3 V3 0.3 x x
14 Group3 V4 1 x x
15 Group3 V5 1 x x
在基础 R 中使用:
a <- data.frame(array2DF(structure(List, dim = length(List))), row.names = 'Var1')
data$Col.E <- a[as.matrix(data[c('Group', 'Variable')])]
data
Col.A Col.B Group Variable Col.E
1 x x Group1 V1 0.857138
2 x x Group1 V2 1
3 x x Group1 V3 0.5
4 x x Group1 V4 not limiting
5 x x Group1 V5 0.1
6 x x Group2 V1 0.65
7 x x Group2 V2 1
8 x x Group2 V3 1
9 x x Group2 V4 0.6
10 x x Group2 V5 0.25
11 x x Group3 V1 0.65
12 x x Group3 V2 0.75
13 x x Group3 V3 0.3
14 x x Group3 V4 1
15 x x Group3 V5 1
请注意,我首先必须更改
List
中的名称以匹配 data
中给出的名称。即将 GROUP1
更改为 Group1
library(rrapply)
library(dplyr)
library(stringr)
rrapply(List, how = "melt") %>%
mutate(L1 = str_to_title(L1)) %>%
left_join(data, ., join_by(Group == L1 , Variable == L2))
#> Col.A Col.B Group Variable value
#> 1 x x Group1 V1 0.857138
#> 2 x x Group1 V2 1
#> 3 x x Group1 V3 0.5
#> 4 x x Group1 V4 not limiting
#> 5 x x Group1 V5 0.1
#> 6 x x Group2 V1 0.65
#> 7 x x Group2 V2 1
#> 8 x x Group2 V3 1
#> 9 x x Group2 V4 0.6
#> 10 x x Group2 V5 0.25
#> 11 x x Group3 V1 0.65
#> 12 x x Group3 V2 0.75
#> 13 x x Group3 V3 0.3
#> 14 x x Group3 V4 1
#> 15 x x Group3 V5 1