使用 NA 条件将一列粘贴到另一列

Paste one column to another with NA conditional

我想将 col3 粘贴到 col1,但避免在 col1 中粘贴 NAs

我的输入:

df <- "col1 col2 col3
       100   x   102
       105   x   106
       101   x   NA"
df <- read.table(text=df, header=T)

我的预期输出:

dfout <- "col1 col2 col3
       102   x   102
       106   x   106
       101   x   NA"
dfout <- read.table(text=dfout, header=T)

有什么想法吗?

听起来,像下面这样的东西应该符合您的描述:

df$col1[!is.na(df$col3)] <- na.omit(df$col3)

或者,但遵循相同的概念,将是:

df$col1 <- replace(df$col1, !is.na(df$col3), na.omit(df$col3))

您可以使用 ifelse():

df$col1 <- ifelse(is.na(df$col3), df$col1, df$col3)

这个也可以和dplyr一起使用:

library(dplyr)
df <- mutate(df, col1 = ifelse(is.na(col3), col1, col3))

我们也可以使用data.table并赋值(:=)到位,这样效率会更高。

library(data.table)
setDT(df)[!is.na(col3), col1:= col3]
df
#  col1 col2 col3
#1:  102    x  102
#2:  106    x  106
#3:  101    x   NA