r - 使用 dplyr 按名称省略列来计算行总和

标签 r dplyr

使用 dplyr,我想计算除一列之外的所有列的行总和。
我设法通过使用列索引来做到这一点。
然而,我想使用列名而不是列索引 .
我怎样才能做到这一点?

示例数据:

# Using dplyr 0.5.0
library(tidyverse)

# Create example data
`UrbanRural` <- c("rural", "urban")
type1 <- c(1582, 671)
type2 <- c(5247, 4123)
type3 <- c(87, 65)
df <- data.frame(`UrbanRural`, type1, type2, type3)
df <- tbl_df(df)
# A tibble: 2 x 5
  UrbanRural type1 type2 type3   tot
      <fctr> <dbl> <dbl> <dbl> <dbl>
  1    rural  1582  5247    87  6916
  2    urban   671  4123    65  4859

有效的示例(使用列索引):
df %>% mutate(tot = rowSums(.[-1]))
# A tibble: 2 x 5
  UrbanRural type1 type2 type3   tot
      <fctr> <dbl> <dbl> <dbl> <dbl>
1      rural  1582  5247    87  6916
2      urban   671  4123    65  4859

我想做的例子:
df %>% mutate(tot = rowSums(select(., -UrbanRural)))

最佳答案

我们可以使用 setdiff选择“UrbanRural”以外的列

df %>%
   mutate(tot = rowSums(.[setdiff(names(.), "UrbanRural")]))
#   UrbanRural type1 type2 type3   tot
#       <fctr> <dbl> <dbl> <dbl> <dbl>
#1      rural  1582  5247    87  6916
#2      urban   671  4123    65  4859

如果我们想使用 select
df %>% 
   select(-one_of("UrbanRural")) %>% 
   rowSums() %>% 
   cbind(df, tot = .) 
#   UrbanRural type1 type2 type3   tot
# 1      rural  1582  5247    87  6916
# 2      urban   671  4123    65  4859

关于r - 使用 dplyr 按名称省略列来计算行总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39598258/

相关文章:

根据重叠模式删除部分字符串

r - 如何使用 getSymbols 下载一组价格并按照请求的顺序存储它们?

r - ggplot2中的color和fill参数有什么区别?

Rstudio 速度慢得令人痛苦

删除组中的值与 R 不匹配的数据框行

r - 有没有办法对不同长度的变量进行 wilcoxon 检验?

R - 如何过滤掉具有唯一标识符的重复数据?

r - 如果使用 apply 和 mutate_at 满足条件,则将自定义函数应用于所选列中的数据

r - 根据R中的频率排序

r - 从数据框中选择具有多列值的唯一组合的行