如果在任何列中找到值,则填充新列 [英] Populate a new column if a value is found in any column

查看:71
本文介绍了如果在任何列中找到值,则填充新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查数据框中的每一行.我需要检查该行中的所有列以查看其是否包含1,如果要填充另一列,该列总结是否有任何列具有1.

I want to check every row in data frame. I need to check all columns in that row to see if it contains a 1, if it does I want to populate another column that summarizes if any of the columns had a 1 or not.

到目前为止,我已经尝试使用grepl通过匹配'1'返回逻辑索引,然后使用ifelse将逻辑向量更改为'yes'或'no'

So far I have tried using grepl to return a logical index by matching the '1', and then with ifelse, change the logical vector to 'yes' or 'no'

dat1$imputed_data <- ifelse(grepl("1", imputed_columns), "yes", "no")

我也尝试过

for(i in nrow(imputed_columns)){
   if (any(imputed_columns[i,])==1)
   {
       dat1$imputed_data[i] <- "yes"
   }else{
       dat1$imputed_data[i] <- "no"
   }
}

我的两次尝试都没有奏效,我认为两者的问题都可能是我指定要进行检入的列的方式.

Both of my attemps have not worked, I think the problem with both might be the way I specify the columns to do the check in.

have:
A B C 
0 0 0
0 1 1
1 0 0
0 0 0

want:
A B C   imputed_data
0 0 0   no
0 1 1   yes
1 0 0   yes
0 0 0   no

请帮助我弄清楚如何进行这项工作.谢谢.

Please help me figure out how to make this work.Thank you in advance.

推荐答案

众多解决方案之一:

a1 = data.frame(A = c(0,0,1,0), B = c(0,1,0,0), C = c(0,1,0,0))

a1$imputed = apply(a1, 1, function(x) ifelse(any(x == 1), 'yes', 'no'))

  A B C imputed
1 0 0 0      no
2 0 1 1     yes
3 1 0 0     yes
4 0 0 0      no

这篇关于如果在任何列中找到值,则填充新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆