将虚拟数据帧转换为数据帧

时间:2018-09-01 19:09:31

标签: r rstudio

我有一个尺寸为 8x12 的虚拟数据帧,我想将x1j中的变量x1x2j中的x2分组和x3j中的x3。创建尺寸为 8x4 的数据框。

set.seed(123)
df <- data.frame(replicate(4,as.factor(sample(1:3,8,rep=TRUE))))

library(dummies)
df.dummy <- dummy.data.frame(df)

我的虚拟数据框

df.dummy
  X11 X12 X13 X21 X22 X23 X31 X32 X33 X41 X42 X43
1   1   0   0   0   1   0   1   0   0   0   1   0
2   0   0   1   0   1   0   1   0   0   0   0   1
3   0   1   0   0   0   1   1   0   0   0   1   0
4   0   0   1   0   1   0   0   0   1   0   1   0
5   0   0   1   0   0   1   0   0   1   1   0   0
6   1   0   0   0   1   0   0   0   1   1   0   0
7   0   1   0   1   0   0   0   1   0   0   0   1
8   0   0   1   0   0   1   0   0   1   0   0   1

预期产量

df
  X1 X2 X3 X4
1  1  2  1  2
2  3  2  1  3
3  2  3  1  2
4  3  2  3  2
5  3  3  3  1
6  1  2  3  1
7  2  1  2  3
8  3  3  3  3

如果我有一个数据帧,其中的列属于类型因子,是否可以使用功能dummy.data.frame()创建一个虚拟数据帧,是否有任何函数可以逆运算?从虚拟到分组的data.frame。

1 个答案:

答案 0 :(得分:5)

df.dummy <- structure(list(X11 = c(1L, 0L, 0L, 0L, 0L, 1L, 0L, 0L), X12 = c(0L, 
0L, 1L, 0L, 0L, 0L, 1L, 0L), X13 = c(0L, 1L, 0L, 1L, 1L, 0L, 
0L, 1L), X21 = c(0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L), X22 = c(1L, 
1L, 0L, 1L, 0L, 1L, 0L, 0L), X23 = c(0L, 0L, 1L, 0L, 1L, 0L, 
0L, 1L), X31 = c(1L, 1L, 1L, 0L, 0L, 0L, 0L, 0L), X32 = c(0L, 
0L, 0L, 0L, 0L, 0L, 1L, 0L), X33 = c(0L, 0L, 0L, 1L, 1L, 1L, 
0L, 1L), X41 = c(0L, 0L, 0L, 0L, 1L, 1L, 0L, 0L), X42 = c(1L, 
0L, 1L, 1L, 0L, 0L, 0L, 0L), X43 = c(0L, 1L, 0L, 0L, 0L, 0L, 
1L, 1L)), .Names = c("X11", "X12", "X13", "X21", "X22", "X23", 
"X31", "X32", "X33", "X41", "X42", "X43"), class = "data.frame",
row.names =  c("1", "2", "3", "4", "5", "6", "7", "8"))

ASSIGN <- gl(4, 3)  ## 4 factor variable; each 3 levels
as.data.frame(lapply(split.default(df.dummy, ASSIGN), max.col))
#  X1 X2 X3 X4
#1  1  2  1  2
#2  3  2  1  3
#3  2  3  1  2
#4  3  2  3  2
#5  3  3  3  1
#6  1  2  3  1
#7  2  1  2  3
#8  3  3  3  3

还有其他生成ASSIGN的方法。基本上,它说明了如何将df.dummy的列分组为正确的因子变量。