Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (5.3k points)
edited by

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 numerous functions (sum, cumsum, rowsum, rowSums, colSums, aggregate, apply) but I can’t make sense of it all.

For example, suppose I have a data frame people with the following columns

Name Height Weight

Mary 65     110

John 70     200

Jane 64     115

How do I get the sum of all the weights?

1 Answer

0 votes
by
edited by

To sum all values in a column of a data frame, you can use the sum() function from the base package as follows:

sum(people$Weight, na.rm = TRUE) 

#na.rm = TRUE will remove all 'NA' values in the column

For example:

df <- data.frame(p=c(10,8,7,3,2,6,7,8),                v=c(100,300,150,400,450,250,150,400))

> df

   p   v

1 10 100

2  8 300

3  7 150

4  3 400

5  2 450

6  6 250

7  7 150

8  8 400

sum(df$p, na.rm = TRUE)

[1] 51

Note - you can get built-in help by using? sum, ?colSums, etc. (by the way, colSums will give you the sum for each column).

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...