我有一个df
id a1 a2
1 x1 y1
2 x2 y2
和另一个数据帧df2
id name1 name2
1 a1 b1
1 a2 b2
2 a3 b3
3 a4 b4
3 a5 b5
df2可以包含来自df1的唯一ID的多个记录。
我需要以这样的方式加入数据帧:对于df1的每一行,我应该从df2的第一个记录中有一列,如果它存在,则从第二个记录开始第二列。
要解释,输出应该是:
id a1 a2 n1 n2
1 x1 y1 a1 a2
2 x2 y2 a3 NA
为此,我使用split
在id上拆分了df2s <- split(df2, df2$id)
但我不确定如何使用sapply。任何指针
答案 0 :(得分:1)
如果我们没有采用'name2'栏
library(dplyr)
df2 %>%
filter(id %in% df$id) %>%
select(-name2) %>%
group_by(id) %>%
mutate(rn = paste0("n", row_number())) %>%
spread(rn, name1) %>%
left_join(df, .)
# id a1 a2 n1 n2
#1 1 x1 y1 a1 a2
#2 2 x2 y2 a3 <NA>
df <- structure(list(id = 1:2, a1 = c("x1", "x2"), a2 = c("y1", "y2"
)), .Names = c("id", "a1", "a2"), class = "data.frame", row.names = c(NA,
-2L))
df2 <- structure(list(id = c(1L, 1L, 2L, 3L, 3L), name1 = c("a1", "a2",
"a3", "a4", "a5"), name2 = c("b1", "b2", "b3", "b4", "b5")), .Names = c("id",
"name1", "name2"), class = "data.frame", row.names = c(NA, -5L))