mutate rowSums exclude one column

前端 未结 3 451
梦毁少年i
梦毁少年i 2021-02-08 10:55

I have a data frame like this

> df
Source: local data frame [4 x 4]

      a x y z
1 name1 1 1 1
2 name2 1 1 1
3 name3 1 1 1
4 name4 1 1 1

W

3条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-08 11:30

    If you want to keep non-numeric columns in the result, you can do this:

    dat %>% mutate(total=rowSums(.[, sapply(., is.numeric)]))
    

    UPDATE: Now that dplyr has scoped versions of its standard verbs, here's another option:

    dat %>% mutate(total=rowSums(select_if(., is.numeric)))
    

    UPDATE 2: With dplyr 1.0, the approaches above will still work, but you can also do row sums by combining rowwise and c_across:

    iris %>% 
      rowwise %>% 
      mutate(row.sum = sum(c_across(where(is.numeric))))
    

提交回复
热议问题