r - 计算一行的某些单元格中有多少个值不是 NA(在 R 中)

标签 r dplyr

我有一个包含很多列的数据框。对于数据框的每一行,我想计算 NA 的列数。问题是我只对一些列感兴趣,并且想要(有效地)调用这些列。

像我在下面的假样本中所做的那样使用 mutate 给了我正确的答案。

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])
    ) %>%
    mutate(
        n_words = 
            as.numeric(!is.na(word1)) + 
            as.numeric(!is.na(word2)) + 
            as.numeric(!is.na(word3)) 
    )

然而,即使是像这样的玩具示例,打字和阅读也是很痛苦的——当我要计算的列数超过 3 列时,这在很大程度上是无用的。是否有更多的 R/dplyr-y 方式来写这个,也许使用 select()样式语法(例如 n_words = !count_blank(word1:word3) )?

我考虑使用 summarize() sans 分组,但是,我需要我正在计算的列中的数据,如果我将它们添加到 group_by ,我在同一条船上再次调用几乎所有的列。

最佳答案

您可以使用 is.na()在选定的列上,然后 rowSums()结果:

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]))

df$word_count <- rowSums( !is.na( df [,3:5]))

df
      id         name    word1     word2   word3 n_words
   <int>        <chr>    <chr>     <chr>   <chr>   <dbl>
1      1        apple        a    actual    <NA>       2
2      2      apricot     able       add    <NA>       2
3      3      avocado    about   address    <NA>       2
4      4       banana absolute     admit   agree       3
5      5  bell pepper   accept advertise    <NA>       2
6      6     bilberry     <NA>    affect    <NA>       1
7      7   blackberry  achieve    afford alright       3
8      8 blackcurrant   across     after    <NA>       2
9      9 blood orange      act afternoon    <NA>       2
10    10    blueberry   active     again   awful       3

编辑

使用 dplyr你可以这样做:
df %>% 
    select(3:5) %>% 
    is.na %>% 
    `!` %>% 
    rowSums

关于r - 计算一行的某些单元格中有多少个值不是 NA(在 R 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39648111/

相关文章:

r - 如何在 R 中创建具有相等随机分布的数据子集

r - 为什么 spplot 为多个面板花费这么多时间

r - 在 deSolve 中的时间步更改参数值

r - 替换列名gsub中的字符

r - 不想显示 ggplot2 中小刻度的所有标签

使用 dplyr 对选定列进行行乘法

r - 如何在R-raster中获得网格周围的等高线?

R dplyr left join - 多个返回值和新行 : how to ask for the first match only?

r - 如何使用 tidyverse : tibble, purrr, dplyr 在列表列上设置名称

r - 在dplyr中,如何删除和重命名不存在的列,操作所有名称,并使用字符串命名新变量?