11
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【R】dplyr mutateの中で複数列名を選択して合計する

Last updated at Posted at 2018-02-03

選んだ列の行だけを足したい

たくさん列があって、バラバラに位置している変数たちの値を合計したいとき

例えば↓の表のうち、aa,vv,ew,ss,の列だけを合計した変数を作りたいとします

image.png

解決策

sample.R


library(dplyr)

df <-  data.frame(ID = c("AA","BB","CC"),
                  a1 = c(NA,2,3),
                  aa = c(1,NA,6),
                  cc = c(NA,2,2),
                  d4 = c(NA,6,NA),
                  vv = c(NA,2,9),
                  dd = c(NA,2,2),
                  ew = c(3,2,NA),
                  ss = c(NA,5,3),
                  kk = c(6,NA,NA)
                  )

  # 合計したい変数名をベクトルで用意する
namelist <- c("aa","vv","ew","ss")

  # one_ofで選択して行を足す
df_added <- df %>% 
  mutate(sum_row = select(., one_of(namelist)) %>% 
                   rowSums(na.rm = T))

# > df_added
# ID a1 aa cc d4 vv dd ew ss kk sum_row
# 1 AA NA  1 NA NA NA NA  3 NA  6       4
# 2 BB  2 NA  2  6  2  2  2  5 NA       9
# 3 CC  3  6  2 NA  9  2 NA  3 NA      18

このくらいの列数だとあまり大変ではないですが、
合計したい列数が多いときは,select(., one_of())からrowSumsにつなげる書き方は便利かなと思いました

詰まった時の助けになれば幸いです
もっと良い方法があれば、是非ご教示ください!

参考

11
7
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
11
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?