Tiptop
Tiptop

Reputation: 623

Calculations in new columns

I have measured the emission of compounds from two soil types on two days.

Now I would like to calculate how much acetone and acetaldehyde contributed to the total emission from each soil type on each day. I want to make a new column in my data where e.g. (acetone emission/total emission) *100 is calculated.

any ideas?

Here's the data

df <- structure(list(soil_type = c("SOC<10", "SOC<10", "SOC<10", "SOC<10", 
"SOC<10", "SOC<10", "SOC>10", "SOC>10", "SOC>10", "SOC>10", "SOC>10", 
"SOC>10"), compound = c("Acetaldehyde", "Acetaldehyde", "Acetone", 
"Acetone", "Total emission", "Total emission", "Acetaldehyde", "Acetaldehyde", 
"Acetone", "Acetone", "Total emission", "Total emission"), day = c(0L, 
4L, 0L, 4L, 0L, 4L, 0L, 4L, 0L, 4L, 0L, 4L), mean = c(0.03, 0.07, 
0.02, 0.04, 0.06, 0.11, 0.01, 0.04, 0.05, 0.07, 0.08, 0.13)), row.names = c(NA, 
-12L), groups = structure(list(soil_type = c("SOC<10", "SOC<10", 
"SOC<10", "SOC>10", "SOC>10", "SOC>10"), compound = c("Acetaldehyde", 
"Acetone", "Total emission", "Acetaldehyde", "Acetone", "Total emission"
), .rows = structure(list(1:2, 3:4, 5:6, 7:8, 9:10, 11:12), ptype = integer(0), class = c("vctrs_list_of", 
"vctrs_vctr", "list"))), row.names = c(NA, -6L), class = c("tbl_df", 
"tbl", "data.frame"), .drop = TRUE), class = c("grouped_df", 
"tbl_df", "tbl", "data.frame"))

Upvotes: 0

Views: 29

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389275

For each soil_type and day you can calculate acetone emission/total emission*100 ratio.

library(dplyr)

df %>%
  group_by(soil_type, day) %>%
  mutate(ratio = mean[match('Acetone', compound)]/
                 mean[match('Total emission', compound)] * 100) %>%
  ungroup -> result

result

#   soil_type compound         day  mean ratio
#   <chr>     <chr>          <int> <dbl> <dbl>
# 1 SOC<10    Acetaldehyde       0  0.03  33.3
# 2 SOC<10    Acetaldehyde       4  0.07  36.4
# 3 SOC<10    Acetone            0  0.02  33.3
# 4 SOC<10    Acetone            4  0.04  36.4
# 5 SOC<10    Total emission     0  0.06  33.3
# 6 SOC<10    Total emission     4  0.11  36.4
# 7 SOC>10    Acetaldehyde       0  0.01  62.5
# 8 SOC>10    Acetaldehyde       4  0.04  53.8
# 9 SOC>10    Acetone            0  0.05  62.5
#10 SOC>10    Acetone            4  0.07  53.8
#11 SOC>10    Total emission     0  0.08  62.5
#12 SOC>10    Total emission     4  0.13  53.8

Upvotes: 1

Related Questions