【问题标题】:R Conditional replacement of NAs based on text in another columnR基于另一列中的文本有条件地替换NA
【发布时间】:2016-07-31 12:27:30
【问题描述】:

R 新手,这让我很难过。

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

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

我想将REST.TYPE 中的NA 替换为Present,但仅当SPECIES = OREST.TYPE 中的NA 替换为NRSPECIES=NR

需要的输出

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

【问题讨论】:

    标签: r replace conditional


    【解决方案1】:

    我们可以使用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))
    

    【讨论】:

      猜你喜欢
      • 2021-08-13
      • 2015-02-01
      • 1970-01-01
      • 2016-03-08
      • 1970-01-01
      • 1970-01-01
      • 2017-01-30
      • 2019-06-01
      • 2018-09-08
      相关资源
      最近更新 更多