Keep a variable deleting an element inside R list that is inside another list

Viewed 64

I have a list with 149 elements. Each element of this list is a list. Each of this list has a dataframe. Each datframe has 11 colunms. Each colunm has 366 values. How do I keep these variables and their structure erasing only the last 336 value?

I have tried to associate NULL value to the last value but I have got an error message

 for (i in 1:149){
     for (j in 1:11){
              x[[i]][[1]][[j]][[366]]   <- NULL
      } 
 }

I expect it would work but it did not: Error in x[[...]] <- m : replacement has length zero

2 Answers

You were close. x[[i]][[1]][[j]][[366]] will try to access the 366th column of the data frame, not the 366th row. Using the <- NULL trick also doesn't work for rows as far as I know.

for (i in 1:149){
     for (j in 1:11){
              x[[i]][[1]] <- x[[i]][[1]][-366,]
      } 
 }

The package purrr can be your friend with lists. This will remove the last row from each data.frame stored in level 2 of the list.

library(purrr)

x2 <- map_depth(x, 2, ~ head(., -1))
Related