Sophia
Sophia

Reputation: 388

Scale each element in a list by a corresponding normalizing factor in R

I have a list as follows (each element is a data frame).

$E9
   time   response
1:  0.0 0.00000000
2:  0.2 0.00826733
3:  0.4 0.01416873
4:  0.6 0.00845066
5:  0.8 0.01258872
6:  1.0 0.01097368

$F12
   time   response
1:  0.0 0.00000000
2:  0.2 0.00703381
3:  0.4 0.00863728
4:  0.6 0.00739067
5:  0.8 0.00786157
6:  1.0 0.00679848

$H1
   time    response
1:  0.0  0.00000000
2:  0.2  0.00142469
3:  0.4 -0.00418229
4:  0.6  0.00361758
5:  0.8  0.00281592
6:  1.0 -0.00293035

I want to multiply each element with a scaling factor, which is stored in a named numeric vector as follows:

F12       H1 
1.033911 1.088928 

For example, I want to multiply the response column of the "F12" element by the element (with the same name) in the vector (1.033911), and if there is no corresponding scaling factor, such as the "E9" element in the list, then I will skip it from being scaled. Thank you for your help.

Upvotes: 0

Views: 294

Answers (2)

Pedro Cavalcante
Pedro Cavalcante

Reputation: 444

Assuming you have that data you describe in a list called original_list and the vector with scaling factors in a vector called scales:

library(tidyverse)

tibble(scale_factors = scales, key = names(scales)) -> 
  scale_factors

tibble(
  values = list,
  key = names(list)) %>%
 left_join(scale_factors) %>%
 mutate(scaled_data = map2(
  .x = values,
  .y = scale_factors,
  ~ mutate(.x, response = response * .y))) ->
 processed_data

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388962

If your list is called list_df and numeric vector as vec we can use Map as :

list_df[names(vec)] <- Map(function(x, y) transform(x, response = response * y), 
                           list_df[names(vec)], vec)

list_df
#$E9
#  time response
#1  0.0 0.000000
#2  0.2 0.008267
#3  0.4 0.014169
#4  0.6 0.008451
#5  0.8 0.012589
#6  1.0 0.010974

#$F12
#  time response
#1  0.0 0.000000
#2  0.2 0.007272
#3  0.4 0.008930
#4  0.6 0.007641
#5  0.8 0.008128
#6  1.0 0.007029

#$H1
#  time  response
#1  0.0  0.000000
#2  0.2  0.001551
#3  0.4 -0.004554
#4  0.6  0.003939
#5  0.8  0.003066
#6  1.0 -0.003191

data

list_df <- list(E9 = structure(list(time = c(0, 0.2, 0.4, 0.6, 0.8, 1), 
    response = c(0, 0.00826733, 0.01416873, 0.00845066, 0.01258872, 
    0.01097368)), class = "data.frame", row.names = c(NA, -6L
)), F12 = structure(list(time = c(0, 0.2, 0.4, 0.6, 0.8, 1), 
    response = c(0, 0.00703381, 0.00863728, 0.00739067, 0.00786157, 
    0.00679848)), class = "data.frame", row.names = c(NA, -6L
)), H1 = structure(list(time = c(0, 0.2, 0.4, 0.6, 0.8, 1), response = c(0, 
0.00142469, -0.00418229, 0.00361758, 0.00281592, -0.00293035)), 
class = "data.frame", row.names = c(NA, -6L)))

vec <- c(F12 = 1.033911, H1= 1.088928)

Upvotes: 2

Related Questions