Hi there I have this data frame (test) and I want to divide every element in the list (AO) by a value in another column (DP):
df <- structure(list(DP = c("572", "594", "625", "594", "537", "513"
), AO2 = list(list(c(2, 2)), list(c(2, 2, 2)), list(c(4, 4)),
list(c(3, 2, 2, 2, 3)), list(c(2, 2)), list(c(2, 2)))), row.names = c(NA,
-6L), class = c("data.table",
"data.frame"))
df
I would like to create a new column in df where each value of the list is divided by the value in df$DP of the same row.

I have tried using mapply but it didn't work. Any idea?
test$AO2_DP <- mapply(FUN = `/`, list(as.numeric(unlist(test$AO2))), as.numeric(test$DP), SIMPLIFY = FALSE)
Base R option using Map -
df$result <- Map(`/`, unlist(df$AO2, recursive = FALSE),df$DP)
df
# DP AO2 result
#1: 572 <list[1]> 0.003496503,0.003496503
#2: 594 <list[1]> 0.003367003,0.003367003,0.003367003
#3: 625 <list[1]> 0.0064,0.0064
#4: 594 <list[1]> 0.005050505,0.003367003,0.003367003,0.003367003,0.005050505
#5: 537 <list[1]> 0.003724395,0.003724395
#6: 513 <list[1]> 0.003898635,0.003898635
If DP value is character in your real data turn it to numeric first by df$DP <- as.numeric(df$DP) before applying the answer.
As the column of lists can be nested you can use rapply to go to each element and make the division.
df$AO2_DP <- Map(function(x, y) rapply(x, function(z) z/y, how="replace"),
df$AO2, as.numeric(df$DP))
df
# DP AO2 AO2_DP
#1 572 2, 2 0.003496503, 0.003496503
#2 594 2, 2, 2 0.003367003, 0.003367003, 0.003367003
#3 625 4, 4 0.0064, 0.0064
#4 594 3, 2, 2, 2, 3 0.005050505, 0.003367003, 0.003367003, 0.003367003, 0.005050505
#5 537 2, 2 0.003724395, 0.003724395
#6 513 2, 2 0.003898635, 0.003898635
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With