Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

divide a column of lists by numbers in another column

Tags:

r

lapply

apply

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.

enter image description here

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)
like image 649
Arol Avatar asked Jan 22 '26 11:01

Arol


2 Answers

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.

like image 90
Ronak Shah Avatar answered Jan 24 '26 10:01

Ronak Shah


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
like image 26
GKi Avatar answered Jan 24 '26 08:01

GKi