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