Count how many values in some cells of a row are not NA (in R)

后端 未结 3 871
小鲜肉
小鲜肉 2020-12-03 23:45

I\'ve got a data frame with lots of columns. For each row of the data frame, I\'d like to get a count of how many columns are NA. The problem is that I\'m only interested in

3条回答
  •  长情又很酷
    2020-12-04 00:31

    library(dplyr)
    library(stringr)
    
    df  <- data_frame(
      id = 1:10
      , name = fruit[1:10]
      , word1 = c(words[1:5],NA,words[7:10])
      , word2 = words[11:20]
      , word3 = c(NA,NA,NA,words[25],NA,NA,words[32],NA,NA,words[65])
    ) 
    
    library(purrr)
    # Rowwise sum of NAs
    df %>% by_row(~ sum(is.na(.)), .collate = 'cols')
    
    # Rowwise sum of non-NAs for word columns
    df %>% 
      select(starts_with('word')) %>% 
      by_row(~ sum(!is.na(.)), .collate = 'cols')
    

提交回复
热议问题