Delete items from a list

advertisements

I have the following list

n = 1:10
s = c("aa", "bb", "cc", "dd", "ee")
b = c(TRUE, FALSE, TRUE, FALSE, FALSE)
x = list(n, s, b, 3)

For a vector v we can remove elements like this: v[-(1:2)]. But how do we go about removing elements from a list? Say that I want x where x[[1]] should now have the last two elements removed - is there an easy way to do this?


We can use head to remove the last two elements of the specific list element by using negative index and update the list

f1 <- function(lst, ind){
           lst[[ind]] <- head(lst[[ind]], -2)
           lst
 }
f1(x, 1)
#[[1]]
#[1] 1 2 3 4 5 6 7 8

#[[2]]
#[1] "aa" "bb" "cc" "dd" "ee"

#[[3]]
#[1]  TRUE FALSE  TRUE FALSE FALSE

#[[4]]
#[1] 3

Or another option using replace in the comments by @Frank

f2 <- function(lst, ind) replace(lst, ind, list(head(lst[[ind]], -2)))