简体   繁体   English

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

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

I have a data frame as:我有一个数据框:

pred预测

   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

I want to create a 4th column that is equal to "Intermediate" if V1 is equal to 1, is labeled as "Long" if V2 is equal to 1, and "Short" if V3 is equal to 1.我想创建第四列,如果 V1 等于 1,则等于“中间”,如果 V2 等于 1,则标记为“长”,如果 V3 等于 1,则标记为“短”。

Thank you谢谢

Base R solution.基础 R 解决方案。 With df==1 we check which elements of the data frame are equal to 1, return the indices of the matches, and then match with a new vector with the desired names.使用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"

Here is another base R approach.这是另一种基本的 R 方法。 If df is your data.frame, you can convert it to a matrix, multiply by a sequence from 1 to number of columns, and create a factor with the desired labels (in the same order as the columns).如果df是您的 data.frame,您可以将其转换为矩阵,乘以从 1 到列数的序列,并创建一个具有所需标签的因子(与列的顺序相同)。

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

Output 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

Maybe you can add new column using the code below也许您可以使用下面的代码添加新列

> 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