R removes objects from a list with if else expression

I have a list of data frames and you want to remove those that have less than 2 rows from my list:

a<-data.frame(x=c(1:4),y=c("m", "n", "o", "p"))
b<-data.frame(x=c(2:6),y=c("q", "w", "e", "r", "t"))
c<-data.frame(x=c(6,7),y=c("j","k"),z=c("$","#"))
d<-data.frame(x="9",y="q",z="+")
mylist<-list(a,b,c,d)

for (i in length(mylist)){
if (nrow(mylist[[i]])<=2){
mylist<-mylist[-i]
}
else{
mylist<-myslit
}}

However, it only seemed to delete data.frame d. The data frame c is still in "mylist" after starting the for loop.

+5
source share
4 answers

You can do this more easily using the application loop:

row_lt2 <- which(sapply(mylist, nrow) < 2)
mylist[-row_lt2]
[[1]]
  x y
1 1 m
2 2 n
3 3 o
4 4 p

[[2]]
  x y
1 2 q
2 3 w
3 4 e
4 5 r
5 6 t

[[3]]
  x y z
1 6 j $
2 7 k #

Note. I use negative indexing to remove items instead of selecting them.

+8
source

To add to the other answers: this is exactly the type that performs the Filterhigher order function for:

> Filter(function(x) {nrow(x) >= 2}, mylist)
[[1]]
  x y
1 1 m
2 2 n
3 3 o
4 4 p

[[2]]
  x y
1 2 q
2 3 w
3 4 e
4 5 r
5 6 t

[[3]]
  x y z
1 6 j $
2 7 k #
+4
source

, for, . for, 2 3, 2 ( 2 , ). repeat while.

a<-data.frame(x=c(1:4),y=c("m", "n", "o", "p"))
b<-data.frame(x=c(2:6),y=c("q", "w", "e", "r", "t"))
c<-data.frame(x=c(6,7),y=c("j","k"),z=c("$","#"))
d<-data.frame(x="9",y="q",z="+")
mylist<-list(a,b,c,d)

i <- 1
while (i <= length(mylist)) {
 if (nrow(mylist[[i]])<=2){
  mylist<-mylist[-i]
 }
 else{
  i <- i+1
 }
}

@Paul...: P

+3

, .

. -, :

for (i in 1:length(mylist))

  for (i seq_along (length (mylist)))

for (i in 4) , , , 4 .

, , . , 4 3. 3 , i 4, subscript out of bounds.

apply, @Paul.

In addition, as opposed to saying otherwise, you can achieve the same thing using a loop for, only your approach should be slightly different:

for (i in 1:length(mylist)) {
    if (nrow(mylist[[i]])>2)
    {
        mylist2[i]<-mylist[i]
    }
}  
print(mylist2)

Here you select list items that are greater than 2 and assign them to the new list. However, it Sapplywill be faster.

+3
source

All Articles