Reputation: 119
I have big data with col_1 as the first category and col_2 as the second category. I am attaching a sample form(refer to the picture below). The data has the first four columns (col_1, col_2, ice, fd). I want to generate the variable "ice_new" for each of the categories of col_1 by taking the sum of the column fd as the denominator and the value of "ice" for different col_2 as the numerator and adding them up. I tried using the "aggregate" function in R, but it doesn't work. How do I execute this in R? Any help will be appreciated
col_1 col_2 ice fd ice_new
A A1 0.3 0.1 (0.3/(0.1+0.4) + 0.2/(0.1+0.4)
A A2 0.2 0.4 (0.3/(0.1+0.4) + 0.2/(0.1+0.4)
B B1 1.2 1 1.2/(1+2+1.2) + 1.4/(1+2+1.2) + 0.6/ (1+2+1.2)
B B2 1.4 2 1.2/(1+2+1.2) + 1.4/(1+2+1.2) + 0.6/ (1+2+1.2)
B B3 0.6 1.2 1.2/(1+2+1.2) + 1.4/(1+2+1.2) + 0.6/ (1+2+1.2)
Upvotes: 0
Views: 302
Reputation: 682
df1 <- data.frame("col_1" = c("A", "A", "B", "B", "B"),
"col_2" = c("A1", "A2", "B1", "B2", "B3"),
"ice" = c(.3,.2,1.2,1.4,.6),
"fd" = c(.1,.4,1,2,1.2))
library(dplyr)
df2 <- df1 %>%
group_by(col_1) %>%
mutate(ice_new=sum(ice)/sum(fd))
df2
## A tibble: 5 x 5
## Groups: col_1 [2]
# col_1 Col_2 ice fd ice_new
# <fct> <fct> <dbl> <dbl> <dbl>
#1 A A1 0.3 0.1 1
#2 A A2 0.2 0.4 1
#3 B B1 1.2 1 0.762
#4 B B2 1.4 2 0.762
#5 B B3 0.6 1.2 0.762
Upvotes: 1
Reputation: 39858
One dplyr
possibility could be:
df %>%
group_by(col_1) %>%
mutate(ice_new = sum(ice/sum(fd)))
col_1 col_2 ice fd ice_new
<chr> <chr> <dbl> <dbl> <dbl>
1 A A1 0.3 0.1 1
2 A A2 0.2 0.4 1
3 B B1 1.2 1 0.762
4 B B2 1.4 2 0.762
5 B B3 0.6 1.2 0.762
Or the same with base R
:
with(df, ave(ice/ave(fd, col_1, FUN = sum), col_1, FUN = sum))
Upvotes: 2
Reputation: 3196
You could also use summarise to get one value per group:
library(dplyr)
df %>%
group_by(col_1) %>%
summarise(ice_new = sum(ice / sum(fd)))
# A tibble: 2 x 2
col1 ice_new
<chr> <dbl>
1 A 1
2 B 0.762
Upvotes: 0