2

Say I have some data created like this

n <- 3
K <- 4
dat <- expand.grid(var1=1:n, var2=1:K)

dat looks like this:

    var1    var2
1     1      1
2     2      1
3     3      1
4     1      2
5     2      2
6     3      2 
7     1      3
8     2      3
9     3      3
10    1      4
11    2      4
12    3      4

I want to remove some rows from both data frames in the list at the same time. Let's say I want to remove the 11th row, and I want the 'gap' to be filled in, so that now the 12th row will become the 11th row.

I understand this is a list of two data frames. Thus the advice here does not apply, since dat[[11]]<-NULL would do nothing, while dat[[2]]<-NULL would remove the second data frame from the list

lapply(dat,"[",11) lets me access the relevant elements, but I don't know how to remove them.

Community
  • 1
  • 1

1 Answers1

2

Assuming that we want to remove rows from a list of data.frames, we loop the list elements using lapply and remove the rows using numeric index.

lapply(lst, function(x) x[-11,])

Or without the anonymous function

lapply(lst, `[`, -11,)

The 'dat' is a data.frame.

is.data.frame(dat)
#[1] TRUE

If we want to remove rows from 'dat',

dat[-11,]

If the row.names also needs to be changed

`row.names<-`(dat[-11,], NULL)

data

lst <- list(dat, dat)
akrun
  • 874,273
  • 37
  • 540
  • 662