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

Filling 3rd column based on value of 2nd column in data frame in R

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

数据框是这样的:

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