r:按值将列拆分为多个列

r:按值将列拆分为多个列,r,reshape,R,Reshape,我有这样一个数据帧: df <- data.frame(first = rep(c("A","B","C","D","E")), second = rep(c(1,2),each=5), third = rnorm(10)) 我想根据列的值将“second”列拆分为2列(第三列的值对应于第二列中的值1,将形成第1列)。所以我会得到: first 1 2 1 A -0.47175662 0.24941514 2 B

我有这样一个数据帧:

df <- data.frame(first = rep(c("A","B","C","D","E")), second = rep(c(1,2),each=5), 
                 third = rnorm(10))
我想根据列的值将“second”列拆分为2列(第三列的值对应于第二列中的值1,将形成第1列)。所以我会得到:

    first    1        2
1   A   -0.47175662 0.24941514
2   B   0.9290547   -0.74557229
3   C   -0.79385274 0.92419408
4   D   0.68175904  0.34787484
5   E   -0.91112323 -0.04578459
我查看了重塑包,但我不知道怎么做。我可以使用xtabs获得类似的表,但我需要的是数据帧,而不是表。

set.seed(1)
set.seed(1)
df <- data.frame(first = rep(c("A","B","C","D","E")), second = rep(c(1,2),each=5), 
                  third = rnorm(10))
library(reshape2)
dcast(df, first ~ second)

#Using third as value column: use value.var to override.
#  first          1          2
#1     A -0.6264538 -0.8204684
#2     B  0.1836433  0.4874291
#3     C -0.8356286  0.7383247
#4     D  1.5952808  0.5757814
#5     E  0.3295078 -0.3053884

df好的,对不起,我找到了方法:

dcast(df, first ~ second, value.var="third")

要在回答中表达度量标准的意见:

reshape(df, direction = "wide", idvar="first", timevar="second")
#   first     third.1     third.2
# 1     A  0.71266631  0.06016044
# 2     B -0.07356440 -0.58889449
# 3     C -0.03763417  0.53149619
# 4     D -0.68166048 -1.51839408
# 5     E -0.32427027  0.30655786

尝试在
wide
方向上重塑

reshape(df, direction = "wide", idvar="first", timevar="second")
#   first     third.1     third.2
# 1     A  0.71266631  0.06016044
# 2     B -0.07356440 -0.58889449
# 3     C -0.03763417  0.53149619
# 4     D -0.68166048 -1.51839408
# 5     E -0.32427027  0.30655786