我想知道是否有人可以建议更好的代码来匹配和转置2个数据帧之间的数据。例如,我有一个数据框
df1 <- structure(list(id = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L), .Label = "A", class = "factor")), .Names = "id", row.names = c(NA,
-12L), class = "data.frame")
id
1 A
2 A
3 A
4 A
5 A
6 A
7 A
8 A
9 A
10 A
11 A
12 A
在此数据框df1
中,我想使用其他数据框data
创建新列df2
:
df2 <- structure(list(id = structure(1:3, .Label = c("A", "B", "C"), class = "factor"),
x1 = c(9L, 4L, 9L), x2 = c(7L, 2L, 8L), x3 = c(7L, 6L, 7L
), x4 = c(9L, 5L, 5L), x5 = c(8L, 8L, 4L), x6 = c(7L, 4L,
6L), x7 = c(9L, 8L, 5L), x8 = c(7L, 7L, 8L), x9 = c(5L, 5L,
5L), x10 = c(4L, 2L, 8L), x11 = c(9L, 1L, 4L), x12 = c(8L,
6L, 5L)), .Names = c("id", "x1", "x2", "x3", "x4", "x5",
"x6", "x7", "x8", "x9", "x10", "x11", "x12"), class = "data.frame", row.names = c(NA,
-3L))
id x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12
1 A 9 7 7 9 8 7 9 7 5 4 9 8
2 B 4 2 6 5 8 4 8 7 5 2 1 6
3 C 9 8 7 5 4 6 5 8 5 8 4 5
基本上,我想首先匹配id
和df1
中的列df2
,然后将df2[,2:13]
中的数据转置到新列df1$data
中结果如下:
result <- structure(list(id = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L), .Label = "A", class = "factor"), data = c(9L,
7L, 7L, 9L, 8L, 7L, 9L, 7L, 5L, 4L, 9L, 8L)), .Names = c("id",
"data"), class = "data.frame", row.names = c(NA, -12L))
id data
1 A 9
2 A 7
3 A 7
4 A 9
5 A 8
6 A 7
7 A 9
8 A 7
9 A 5
10 A 4
11 A 9
12 A 8
我可以用
来实现结果df1$data <- t(df2[unique(match(df1$id, df2$id)),2:13])
但这对我来说似乎“混乱”......任何人都可以告诉我,如果有更好/更短/更直观的方式我应该这样做吗?