繁体   English   中英

基于 R 中的其他列创建新列

[英]creating a new column based on other columns in R

我有一个数据框:

预测

   V1 V2 V3
2   0  1  0
4   0  0  1
5   0  0  1
8   0  0  1
11  0  1  0
16  0  1  0
20  1  0  0
21  0  1  0
24  0  1  0
26  0  1  0
31  0  0  1
32  1  0  0
34  1  0  0

我想创建第四列,如果 V1 等于 1,则等于“中间”,如果 V2 等于 1,则标记为“长”,如果 V3 等于 1,则标记为“短”。

谢谢

基础 R 解决方案。 使用df==1我们检查数据帧的哪些元素等于 1,返回匹配项的索引,然后与具有所需名称的新向量匹配。

tmp=which(df==1,arr.ind=T)    
tmp=tmp[order(tmp[,"row"]),]
c("Intermediate","Long","Short")[tmp[,"col"]]

 [1] "Long"         "Short"        "Short"        "Short"        "Long"        
 [6] "Long"         "Intermediate" "Long"         "Long"         "Long"        
[11] "Short"        "Intermediate" "Intermediate"

这是另一种基本的 R 方法。 如果df是您的 data.frame,您可以将其转换为矩阵,乘以从 1 到列数的序列,并创建一个具有所需标签的因子(与列的顺序相同)。

df$new <- factor(as.matrix(df) %*% (1:ncol(df)), 
                 labels = c("Intermediate", "Long", "Short"))

Output

R> df
   V1 V2 V3          new
1   0  1  0         Long
2   0  0  1        Short
3   0  0  1        Short
4   0  0  1        Short
5   0  1  0         Long
6   0  1  0         Long
7   1  0  0 Intermediate
8   0  1  0         Long
9   0  1  0         Long
10  0  1  0         Long
11  0  0  1        Short
12  1  0  0 Intermediate
13  1  0  0 Intermediate

也许您可以使用下面的代码添加新列

> c("Intermediate", "Long", "Short")[rowSums(col(df) * df)]
 [1] "Long"         "Short"        "Short"        "Short"        "Long"        
 [6] "Long"         "Intermediate" "Long"         "Long"         "Long"
[11] "Short"        "Intermediate" "Intermediate

暂无
暂无

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

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