Reputation: 47
I am very new to R and especially to R apply
family functions.
I have a data frame:
df <- data.frame(a=c(1,2,3),b=c(3,4,5))
And tried:
lapply(df$a,sum)
But this doesn't give the sum of the first column of data frame df
.
However, this line of code does:
lapply(df,sum)
Is there something that I am doing wrong here?
Upvotes: 1
Views: 39
Reputation: 886948
For multiple columns, use colSums
colSums(df, na.rm = TRUE)
and single column, it would be
sum(df$a, na.rm = TRUE)
If we loop over a vector, each element of the list
have a length of 1, thus the sum
would be the element itself
Upvotes: 1