How to sum data.frame column values?

后端 未结 4 1586
梦谈多话
梦谈多话 2020-12-07 15:13

I have a data frame with several columns; some numeric and some character. How to compute the sum of a specific column? I’ve googled for this and I see nume

4条回答
  •  独厮守ぢ
    2020-12-07 16:01

    To sum values in data.frame you first need to extract them as a vector.

    There are several way to do it:

    # $ operatior
    x <- people$Weight
    x
    # [1] 65 70 64
    

    Or using [, ] similar to matrix:

    x <- people[, 'Weight']
    x
    # [1] 65 70 64
    

    Once you have the vector you can use any vector-to-scalar function to aggregate the result:

    sum(people[, 'Weight'])
    # [1] 199
    

    If you have NA values in your data, you should specify na.rm parameter:

    sum(people[, 'Weight'], na.rm = TRUE)
    

提交回复
热议问题