PythonSOS
PythonSOS

Reputation: 359

Add new rows in list of lists with conditions in R

I have a list of lists testFrame that looks like:

d1 <- data.frame(var1 = c(10, 7), var2 = c(20,2), var3 = c(30,1))
d2 <- data.frame(var1 = c(20,1), var2 = c(30,2), var3 = c(40,3))
testFrame <- list(d1, d2)
[[1]]
    var1 var2 var3
  1   10   20   30
  2    7    2    1

[[2]]
    var1 var2 var3
  1   20   30   40
  2    1    2    3

I want to add two new rows to each list, where if it's the first column in the list, the 3rd row will be the max value between row 1 and 2, and the 4th row is the min value. Else, the third row will be the number from the fourth row in the previous column, and the fourth row is that number minus the min number from that column.

The result should look like:

[[1]]
    var1 var2 var3
  1   10   20   30
  2    7    2    1
  3   10    7    5
  4    7    5    4

[[2]]
    var1 var2 var3
  1   20   30   40
  2    1    2    3
  3   20    1   -1
  4    1   -1   -4

So far, I have

addRows<- lapply (testFrame,
                  function(x)
                    for(i in 1:3) {
                     if (i==1) {rbind.......}
                     else {
                       rbind(.........)
                     }
                    }
                   )  

I'm getting stuck at what to put in the rbind.

Upvotes: 1

Views: 295

Answers (1)

DataM
DataM

Reputation: 351

my_df <- data.frame("var1" = c(10, 7),
                "var2" = c(20, 2),
                "var3" = c(30, 1),
                "var4" = c(40, 7),
                stringsAsFactors = FALSE)

my_df2 <- data.frame("var1" = c(10, 18),
                 "var2" = c(20, 2),
                 "var3" = c(30, 1),
                 "var4" = c(40, 7),
                 stringsAsFactors = FALSE)

my_df3 <- data.frame("var1" = c(10, 20),
                 "var2" = c(20, 2),
                 "var3" = c(30, 1),
                 "var4" = c(40, 7),
                 stringsAsFactors = FALSE)

my_list <- list(my_df, my_df2, my_df3)

my_third <- function(x, y) {
if (x == 1) {
my_result <- max(my_list[[y]]$var1)
} else if (x == 2) {
my_result <- my_list[[y]][2, 1]
} else {
my_result <- my_list[[y]][2, x - 2] - my_list[[y]][2, x - 1]
}
return (my_result)
}
my_fourth <- function(x, y) {
if (x == 1) {
my_result <- min(my_list[[y]]$var1)
} else {
my_result <- my_list[[y]][3, x] - my_list[[y]][2, x]
}
return (my_result)
}
my_f <- function(y) {
my_a <- lapply(1:ncol(my_list[[y]]), function(x) my_third(x, y))
my_list[[y]] <<- rbind(my_list[[y]], my_a)
my_a <- lapply(1:ncol(my_list[[y]]), function(x) my_fourth(x, y))
my_list[[y]] <<- rbind(my_list[[y]], my_a)
}
my_list2 <- lapply(1:length(my_list), my_f)
my_list2[[1]]
my_list2[[2]]
my_list2[[3]]

Edit: Change the code so it can handle a list of dataframe

Upvotes: 1

Related Questions