【问题标题】:Getting the rownumbers for all NA values of a column获取列的所有 NA 值的行号
【发布时间】:2021-12-18 15:44:22
【问题描述】:

我的数据如下:

df <- as.data.frame(c(1,2,NA,4,5))
names(df)[1] <- "first_column"

  first_column
1            1
2            2
3           NA
4            4
5            5

我想获取first_columnNA 的所有行号,所以3

我找到了查找其他值的方法,即which(grepl(2, df$first_column)) 但不是NA。包含NA 值显然很麻烦(link)。 有没有更简单的方法来做到这一点?

有什么想法吗?

【问题讨论】:

  • 你在找is.na

标签: r na grepl


【解决方案1】:

我们可以使用whichis.na

which(is.na(df))
[1] 3

【讨论】:

    【解决方案2】:
    which(is.na(df$first_column)==T)
    

    【讨论】:

    • 代码在附有解释时会更有帮助。 Stack Overflow 是关于学习的,而不是提供 sn-ps 来盲目复制和粘贴。请edit您的问题并解释它如何回答所提出的具体问题。见How to Answer
    【解决方案3】:

    使用tidyverse 方法:

    library(tidyverse)
    
    df <- as.data.frame(c(1,2,NA,4,5))
    names(df)[1] <- "first_column"
    
    df %>% 
      mutate(second_column = ifelse(is.na(first_column), row_number(), NA))
    
    #>   first_column second_column
    #> 1            1            NA
    #> 2            2            NA
    #> 3           NA             3
    #> 4            4            NA
    #> 5            5            NA
    

    【讨论】:

      猜你喜欢
      • 2018-10-21
      • 1970-01-01
      • 2019-12-15
      • 2020-12-04
      • 1970-01-01
      • 1970-01-01
      • 2022-01-16
      • 2020-06-27
      • 2021-10-29
      相关资源
      最近更新 更多