Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.2k views
in Technique[技术] by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...