R 基于现有值创建虚拟分类列
参考: 跟进这个问题。虽然model.matrix和data.table都可以很好地处理其中已有的值,但我们如何使用它们来模拟列 也就是说,从同一数据帧中的数据R 基于现有值创建虚拟分类列,r,R,参考: 跟进这个问题。虽然model.matrix和data.table都可以很好地处理其中已有的值,但我们如何使用它们来模拟列 也就是说,从同一数据帧中的数据 data <- read.table(header=T, text=' subject weight sex test 1 2 M control 2 3 F cond1
data <- read.table(header=T, text='
subject weight sex test
1 2 M control
2 3 F cond1
3 2 F cond2
4 4 M control
5 3 F control
6 2 F control
')
使输出达到:
subject weight control_F_M control_M condtrol_F cond1_F_M cond1_F cond1_M
1 2 0 1 0 0 0 0
2 3 0 0 1 0 0 0
3 2 0 0 0 0 1 0
4 4 0 1 0 0 0 0
5 3 1 0 0 0 0 0
6 2 1 0 0 0 0 0
知道如何在R中生成“Control\u F\M”和Cond1\u F\M列吗
提前感谢,,
蜜蜂
编辑:
为了生成上述输出,我使用前面建议的数据表&dcast
如果我知道列:test中的所有值,我可以使用If-Else。我很抱歉没有早些澄清这一点。当然,这个专栏的挑战在于它是动态的,所以我希望动态地生成这么多的专栏,作为下面的扩展,或者使用类似的方法
dcast(data, subject+weight~test+sex, fun=length, drop=c(TRUE,FALSE))
data$F_M_控制请参见此处:
dcast(data, subject+weight~test+sex, fun=length, drop=c(TRUE,FALSE))