根据R中数据帧中第二列的值填充第三列
我想检查数据框的第二列是否有空值,并相应地填充第三列,称为“标签” 数据帧如下所示:根据R中数据帧中第二列的值填充第三列,r,if-statement,vectorization,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,]$l
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" }
}
}
for(i in nrow(数据帧)){
if(isTRUE(数据帧[i,c('col2')]===“”)(真)
{dataframe[i,]$label和ifelse
是一种解决方案(如David所述)。ifelse
是矢量化的,如下所示:
df$label <- ifelse( df$col2=='', 'col2_empty', 'both_filled' )
或使用常规子集的另一种方式:
#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'
请看一下?ifelse
,令人惊讶的是,尽管有或也有,但我找不到直接的副本。
#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'
> df
col1 col2 label
1 hello there both_filled
2 this that both_filled
3 start col2_empty