Daniel
Daniel

Reputation: 1272

How to identify the objects of a list with >1 rows in R?

I'd like to know how to identify the objects of a list with >1 rows in R?

as example let's say we have the following list:

 c = 6:10
 d = 1:5
 f = 11:15

output <- list(var1 = rbind(c,d,f), var2 = c, var3 = rbind(d,f))
output

$var1
  [,1] [,2] [,3] [,4] [,5]
c    6    7    8    9   10
d    1    2    3    4    5
f   11   12   13   14   15

$var2
[1]  6  7  8  9 10

$var3
  [,1] [,2] [,3] [,4] [,5]
d    1    2    3    4    5
f   11   12   13   14   15

The expected is to have a file either list or provide the name of object with > 1 row as following:

output2
 $var1
  [,1] [,2] [,3] [,4] [,5]
c    6    7    8    9   10
d    1    2    3    4    5
f   11   12   13   14   15

$var3
  [,1] [,2] [,3] [,4] [,5]
d    1    2    3    4    5
f   11   12   13   14   15

or

output2 
[1] var1, var3

Thanks in advance for your help with explanations!

Upvotes: 0

Views: 86

Answers (4)

Lucy
Lucy

Reputation: 991

There are likely many ways to do this, but this should work:

output2 <- names(which(unlist(purrr::map(output, ~nrow(.x)>1))==TRUE))

Upvotes: 1

Iaroslav Domin
Iaroslav Domin

Reputation: 2718

An elegant solution with purrr:

library(purrr)    
keep(output, ~ (nrow(.) %||% 1) > 1) 

NULLs may appear (and do appear in your example) when we apply nrow to a 1-dimensional objects. So this %||% 1 is here to replace NULLs with 1.

Or a bit more like @lmo's approach:

keep(output, ~ isTRUE(nrow(.) > 1))

Upvotes: 1

user4148072
user4148072

Reputation:

Here is another idea:

c = t(6:10)
d = t(1:5)
f = t(11:15)

output <- list(var1 = rbind(c,d,f), var2 = c, var3 = rbind(d,f))
output

nrow(as.data.frame(output[1]))>1
nrow(as.data.frame(output[2]))>1
nrow(as.data.frame(output[3]))>1

f <- function(x) nrow(as.data.frame(x))>1
sapply(output, f)
which(sapply(output, f))

I think you need to take the transpose function t() of the original vectors here to ensure that they are treated as one row with many columns, rather than many columns with one row.

Upvotes: 1

lmo
lmo

Reputation: 38510

You can do this with sapply, dim, isTRUE, and [ in base R:

output[sapply(output, function(i) isTRUE(dim(i)[1] > 1))]
$var1
  [,1] [,2] [,3] [,4] [,5]
c    6    7    8    9   10
d    1    2    3    4    5
f   11   12   13   14   15

$var3
  [,1] [,2] [,3] [,4] [,5]
d    1    2    3    4    5
f   11   12   13   14   15

sapply runs through each object and checks if the row dimension, first element of dim, is greater than 1. However, as vectors and some other objects (eg, lists) do not have a dimension attribute, this check returns logical(0). To coerce a FALSE out of this, we wrap the output in isTRUE. The logical vector resulting from sapply is used to subset the list.

Upvotes: 2

Related Questions