'Using list to sum a dataframe in R
Consider the following dataframe in R:
df <- data.frame(Industry = c("Agriculture", "Fishery", "Industry"),
Value = c(10,20,30))
Consider I want to sum the value for "Agriculture" and "Fishery" (10 + 20 = 30). For example, I could do it like this:
df$Value[df$Industry == "Agriculture"] + df$Value[df$Industry == "Fishery"]
However, instead I want to create list with "Agriculture" and "Fishery", and thereafter summing the value. Because in my example I have a big data.frame, and that will make it a lot easier. How to do that?
Solution 1:[1]
For completeness, a tidyverse approach:
df <- data.frame(Industry = c("Agriculture", "Fishery", "Industry"),
Value = c(10, 20, 30))
df %>% filter(Industry %in% c("Agriculture", "Fishery")) %>%
summarise(sumValue=sum(Value))
Output:
sumValue
1 30
Solution 2:[2]
A data.table() approach
library(data.table)
DT <- data.table(Industry = c("Agriculture", "Fishery", "Industry"),
Value = c(10,20,30))
DT[Industry != "Industry"][, sum(Value)]
Output
> [1] 30
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | January |
| Solution 2 | Jose |
