【问题标题】:replace NA values with sequence用序列替换 NA 值
【发布时间】:2022-06-16 00:07:38
【问题描述】:

我正在尝试填充字符串的一些 NA 值,但计算正在填充的 NA 值。

例如我有以下字符串:

string = c("A", "B", "C", NA, NA, "D", "E", NA, "F", "G", NA, NA)

预期输出:

"A", "B", "C", "NA_VALUE_1", "NA_VALUE_2", "D", "E", "NA_VALUE_3", "F", "G", "NA_VALUE_4", "NA_VALUE_5"

所以,我想粘贴序列paste("NA_VALUE_", valueHere),其中valueHere 增加。

【问题讨论】:

    标签: r


    【解决方案1】:
    n_na = sum(is.na(string))
    string[is.na(string)] <- paste0("NA_VALUE_", seq_len(n_na))
    

    【讨论】:

      【解决方案2】:

      你可以试试

      ifelse(is.na(string), paste0("NA_VALUE_", cumsum(is.na(string))), string)
      

      【讨论】:

        【解决方案3】:

        另一种可能的解决方案:

        string[is.na(string)] <- paste0("NA_Value_", 1:sum(is.na(string)))
        string
        
        #>  [1] "A"          "B"          "C"          "NA_Value_1" "NA_Value_2"
        #>  [6] "D"          "E"          "NA_Value_3" "F"          "G"         
        #> [11] "NA_Value_4" "NA_Value_5"
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-10-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-06-28
          • 2015-04-26
          • 2019-03-14
          相关资源
          最近更新 更多