有没有办法使用 rowSums 和 is.numeric 只对数字列求和?

Dav*_*veM 3 r dplyr mutate

一个快速的问题,希望能快速回答。

我试图仅在具有数字数据的列上使用 rowSums。我想做一些与此等效的事情(使用内置数据集 CO2 作为可重现的示例):

# Reproducible example  
CO2 %>%
  mutate( Total = rowSums(.[c(-1, -2, -3)]) ) %>% 
  head()

  Plant   Type  Treatment conc uptake Total
1   Qn1 Quebec nonchilled   95   16.0 111.0
2   Qn1 Quebec nonchilled  175   30.4 205.4
3   Qn1 Quebec nonchilled  250   34.8 284.8
4   Qn1 Quebec nonchilled  350   37.2 387.2
5   Qn1 Quebec nonchilled  500   35.3 535.3
6   Qn1 Quebec nonchilled  675   39.2 714.2
Run Code Online (Sandbox Code Playgroud)

我用 mutate 和 is.numeric 尝试了 rowSums,但没有成功。是否有捷径可寻?

# How do sum rows using is.numeric (below does not work)?                 
CO2 %>%
  mutate( Total = rowSums(., is.numeric(.)) )
Run Code Online (Sandbox Code Playgroud)

akr*_*run 6

我们可以使用select_ifrowSums

library(dplyr)
CO2 %>% 
    mutate(Total = rowSums(select_if(., is.numeric), na.rm = TRUE)) %>%
    head
#  Plant   Type  Treatment conc uptake Total
#1   Qn1 Quebec nonchilled   95   16.0 111.0
#2   Qn1 Quebec nonchilled  175   30.4 205.4
#3   Qn1 Quebec nonchilled  250   34.8 284.8
#4   Qn1 Quebec nonchilled  350   37.2 387.2
#5   Qn1 Quebec nonchilled  500   35.3 535.3
#6   Qn1 Quebec nonchilled  675   39.2 714.2
Run Code Online (Sandbox Code Playgroud)


小智 6

我知道这是一篇旧文章,但select_if现在已被 cross 取代,因此您可以像这样使用它:CO2 %>% mutate(total = rowSums(across(where(is.numeric))))