根据R中数据框中第2列的值填充第3列

时间:2015-02-03 22:20:27

标签: 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" }
  }
}

但我获得的每一行都是相同的标签

1 个答案:

答案 0 :(得分:2)

使用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
相关问题