通过不同的行值将多行合并到一个列中
Merging multiple rows by disticnt row value into a single column
使用 R 尝试合并原始矩阵以生成基于行值的矩阵。
例如:
来自:
1 2
a1 10
a1 20
a1 40
a2 45
a2 50
a3 40
a4 45
a4 60
至:
10 20 40
45 50
40
45 60
我们可以使用split
split(df1[,2], df1[,1])
#$a1
#[1] 10 20 40
#$a2
#[1] 45 50
#$a3
#[1] 40
#$a4
#[1] 45 60
创建 list
的 vectors
或使用aggregate
:
aggregate(df$X2~df$X1, df, rbind)
# df$X1 df$X2
# 1 a1 10, 20, 40
# 2 a2 45, 50
# 3 a3 40
# 4 a4 45, 60
数据
df <- structure(list(X1 = structure(c(1L, 1L, 1L, 2L, 2L, 3L, 4L, 4L
), .Label = c("a1", "a2", "a3", "a4"), class = "factor"), X2 = c(10L,
20L, 40L, 45L, 50L, 40L, 45L, 60L)), .Names = c("X1", "X2"), class =
"data.frame", row.names = c(NA,
-8L))
使用 R 尝试合并原始矩阵以生成基于行值的矩阵。
例如:
来自:
1 2
a1 10
a1 20
a1 40
a2 45
a2 50
a3 40
a4 45
a4 60
至:
10 20 40
45 50
40
45 60
我们可以使用split
split(df1[,2], df1[,1])
#$a1
#[1] 10 20 40
#$a2
#[1] 45 50
#$a3
#[1] 40
#$a4
#[1] 45 60
创建 list
的 vectors
或使用aggregate
:
aggregate(df$X2~df$X1, df, rbind)
# df$X1 df$X2
# 1 a1 10, 20, 40
# 2 a2 45, 50
# 3 a3 40
# 4 a4 45, 60
数据
df <- structure(list(X1 = structure(c(1L, 1L, 1L, 2L, 2L, 3L, 4L, 4L
), .Label = c("a1", "a2", "a3", "a4"), class = "factor"), X2 = c(10L,
20L, 40L, 45L, 50L, 40L, 45L, 60L)), .Names = c("X1", "X2"), class =
"data.frame", row.names = c(NA,
-8L))