繁体   English   中英

在R中转置并创建分类值

[英]Transpose and create categorical values in R

我有一个具有以下结构的数据框,我希望从中将变量转置为类别。 目的是找到变量的加权混合。

       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
               ')

      data

预期产量:

          subject weight control_F control_M cond1_F cond1_M cond2_F cond2_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

我尝试使用ifelse和cut的组合,但无法产生输出。

关于如何执行此操作的任何想法?

TIA

您可以使用

model.matrix(~ subject + weight + sex:test - 1, data)

我认为model.matrix在这里是最自然的(请参阅@Julius的答案),但这是另一种选择:

library(data.table)
setDT(data)

dcast(data, subject+weight~test+sex, fun=length, drop=c(TRUE,FALSE))


   subject weight cond1_F cond1_M cond2_F cond2_M control_F control_M
1:       1      2       0       0       0       0         0         1
2:       2      3       1       0       0       0         0         0
3:       3      2       0       0       1       0         0         0
4:       4      4       0       0       0       0         0         1
5:       5      3       0       0       0       0         1         0
6:       6      2       0       0       0       0         1         0

要以“正确”顺序获得列(首先使用控件),请在投射前设置因子水平:

data[, test := relevel(test, "control")]
dcast(data, subject+weight~test+sex, fun=length, drop=c(TRUE,FALSE))


   subject weight control_F control_M cond1_F cond1_M cond2_F cond2_M
1:       1      2         0         1       0       0       0       0
2:       2      3         0         0       1       0       0       0
3:       3      2         0         0       0       0       1       0
4:       4      4         0         1       0       0       0       0
5:       5      3         1         0       0       0       0       0
6:       6      2         1         0       0       0       0       0

(注意:reshape2的dcast在这里不太好,因为它的drop选项适用于行和列。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM