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

前端 未结 2 735
一生所求
一生所求 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
    
    0 讨论(0)
  • 2021-01-27 11:36

    I ended up using this code:

    df$SUMCOL <- rowSums(df[sapply(df, is.numeric)], na.rm = TRUE)

    0 讨论(0)
提交回复
热议问题