使用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)
Run Code Online (Sandbox Code Playgroud)
# 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
Run Code Online (Sandbox Code Playgroud)
有效的示例(使用列索引):
df %>% mutate(tot = rowSums(.[-1]))
Run Code Online (Sandbox Code Playgroud)
# 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
Run Code Online (Sandbox Code Playgroud)
我想做的例子:
df %>% mutate(tot = rowSums(select(., -UrbanRural)))
Run Code Online (Sandbox Code Playgroud)
我们可以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
Run Code Online (Sandbox Code Playgroud)
如果我们想使用 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
473 次 |
| 最近记录: |