开发者

R: add different values to columns within a list of dataframes

开发者 https://www.devze.com 2023-03-29 21:35 出处:网络
If I have a list like: list <- list( \"1\" = data.frame(time=1:3, temp = sample(11:13)), \"3\" = data.frame(time=1:3, temp = sample(11:13)))

If I have a list like:

list <- list( "1" = data.frame(time=1:3, temp = sample(11:13)),
              "3" = data.frame(time=1:3, temp = sample(11:13)))

list

$`1`
  time temp
1    1   11
2    2   12
3    3   13

$`3`
  time temp
1    1   11
2    2   12
3    3   13

Now I want to add a correction-value to columns temp, +1 for dataframe 1 and -1 for dataframe 3, so the result would be:

$`1`
  time temp
1    1   12
2    2   13
3    3   14

$`3`
  time temp
1    1   10
2    2   11
3    3   12

Let´s additionally assume I have multiple of those lists, where sometimes dataframe 3 or 1 may be missing, or even a dataframe 2 maybe included, which would need its own correction-factor... I tried strange things for dataframe 1:

list <- lapply(list, function(开发者_Go百科x)   {x <- x$"1"$temp-1;x})

or

list <- lapply(list, function(x)   {x <- x[x$temp+1,];x})

also tried to add a seq_along for the other dataframe in the list...nothing works, maybe because I don´t quite understand how the syntax works...


I changed the name of the data structure to dflist. It's just wrong to call a list "list". You also need some data structure to pull in the associated correction factors, so let's posit one with the same names as "dflist":

dflist <- list( "1" = data.frame(time=1:3, temp = sample(11:13)),
              "3" = data.frame(time=1:3, temp = sample(11:13)))

corrlist <- list("1" = 1, "3"=-1) 

# Replaced lapply with for loop
for( nam in names(dflist)) {
        dflist[[nam]]['temp'] <- dflist[[nam]]['temp'] +corrlist[[nam]]
                            }
 dflist
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号