LoginSignup
1
1

More than 1 year has passed since last update.

【R】tibbleの行ごとに各列の値を合算したい

Last updated at Posted at 2021-07-10

Rでgroup_byしているtibble型のデータを列ごとに合算するのは、summarize(Sum = sum(x1))で簡単に実施できる。
しかし、行ごとに計算する方法がわからなかった。

以下のような z がある。

> library(tidyverse)
> z <- tibble(x1=c(1, 2), x2=c(9L, 6L), x3=c(2, 2), x4=c(0.9, 0.6))
> z
# A tibble: 2 x 4
     x1    x2    x3    x4
  <dbl> <int> <dbl> <dbl>
1     1     9     2   0.9
2     2     6     2   0.6

このzで、x2,x3,x4を足したSum行を作成したい。

  x1 x2 x3  x4  Sum
1  1  9  2 0.9 11.9
2  2  6  2 0.6  8.6

そのやり方を二つ考えた。

#1:for文の活用
s <- numeric(nrow(z))
for(i in 2:ncol(z)){
  s <- s + z[[i]]
}
z <- transform(z, Sum = s)

#2:selectでx1を削除してからrowSumsで合計
z %>%
  select(-x1) %>%
  rowSums() -> zz
z %>%
  add_column(Sum = zz) -> z
1
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1