How do I make a column that sums only numeric columns?

前端 未结 2 739
一生所求
一生所求 2021-01-27 10:41

I have a dataframe with a lot of columns.

LABEL    COL1  COL2  COL3
Meat     10    20    30
Veggies  20    30    40

How do I make column named

2条回答
  •  说谎
    说谎 (楼主)
    2021-01-27 11:20

    You can use this function, which takes advantage of select_if and scoped argument is_numeric

    myfun <- function(df) {
                   require(dplyr)
                   y <- select_if(df, is_numeric)
                   rowSums(y, na.rm=T)
             }
    

    Solution

    df$SUMCOL <- myfun(df)
    

    Output

        LABEL COL1 COL2 COL3 SUMCOL
    1    Meat   10   20   30     60
    2 Veggies   20   30   40     90
    

提交回复
热议问题