R 根据另一列中的文本有条件地替换 NA

R Conditional replacement of NAs based on text in another column

R 的新手,这让我很困惑。

我有一个 data.frame 看起来像这样。

SPECIES   REST.TYPE
O         NA
O         Long
NR        NA
O         Short
NR        NA
O         NA

我想将 REST.TYPE 中的 NA 替换为 Present,但仅当 SPECIES = O 时才替换 NA 中的 REST.TYPENRSPECIES=NR

需要输出

SPECIES   REST.TYPE
O         Present
O         Long
NR        NR
O         Short
NR        NR
O         Present

我们可以使用data.table。将 'data.frame' 转换为 'data.table' (setDT(df1))。根据 "O" 的 "SPECIES" 值和 "REST.TYPE" 中的 NA 元素,我们将 "REST.TYPE" 分配给 "Present"。然后,我们根据 'REST.TYPE'

中剩余的 NA 值将 'REST.TYPE' 分配 (:=) 给 'SPECIES'
library(data.table)
setDT(df1)[is.na(REST.TYPE) & SPECIES=="O", REST.TYPE := "Present"]
df1[is.na(REST.TYPE), REST.TYPE := SPECIES]
df1
#   SPECIES REST.TYPE
#1:       O   Present
#2:       O      Long
#3:      NR        NR
#4:       O     Short
#5:      NR        NR
#6:       O   Present

我们也可以用 base R 使用 ifelse

with(df1, ifelse(SPECIES=="O" & is.na(REST.TYPE), "Present", 
          ifelse(is.na(REST.TYPE), SPECIES, REST.TYPE)))
#[1] "Present" "Long"    "NR"      "Short"   "NR"      "Present"

数据

df1 <- structure(list(SPECIES = c("O", "O", "NR", "O", "NR", "O"), 
REST.TYPE = c(NA, 
"Long", NA, "Short", NA, NA)), .Names = c("SPECIES", "REST.TYPE"  
), class = "data.frame", row.names = c(NA, -6L))