r - 根据R中数据框中第二列的值填充第三列

标签 r if-statement vectorization

我想检查我的数据框的第二列是否有空值,并相应地填充名为“标签”的第三列。

数据框是这样的:

col1   col2   label
hello  there  both filled
this   that   both filled 
start  ""     col2 empty

我正在尝试:

for (i in nrow(dataframe)) {

if (isTRUE(dataframe[i,c('col2')] == "") == TRUE) 
   { dataframe[i,]$label <- "both filled" }
else{
   dataframe[i,]$label <- "col2 empty" }
  }
}

但我得到的只是每一行的相同标签

最佳答案

ifelse 是一种解决方案(正如 David 所提到的)。 ifelse 已矢量化,如下所示:

df$label <- ifelse( df$col2=='',  'col2_empty',  'both_filled' )

输出1:

> df
   col1  col2       label
1 hello there both_filled
2  this  that both_filled
3 start        col2_empty

或者使用常规子集的不同方式:

#add col2_empty for empty second column first
df$label[df$col2==''] <- 'col2_empty'    
#add both_filled for filled second column 
df$label[!df$col2==''] <- 'both_filled'

输出2:

> df
   col1  col2       label
1 hello there both_filled
2  this  that both_filled
3 start        col2_empty

关于r - 根据R中数据框中第二列的值填充第三列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28309880/

相关文章:

c++ - 使用 #define 处理 if 语句错误

php - 使用php循环遍历mysql表,为什么elseif语句不起作用?

python - Numpy 向量化错误

python - 从向量创建矩阵,其中每一行都是向量的移位版本

python - 创建在 2D numpy 数组中充当分组样式查找的字典的最快方法?

r - 将图像添加到弹性表并使用 Rmarkdown 在 Word 文档中生成我的弹性表

r - 使用 rhighcharts 在 y 轴上绘制百分比?

R data.table - 如何使用分配的变量作为列名来计算摘要_和_分组

r - 要计算时间差,有没有办法改变所有: in a data frame?

c++ - 编译器 : What if condition is always true/false