P_Grace
P_Grace

Reputation: 107

How can I find the index of objects with length of 1 in a list?

I have a list of objects and each object is of varying lengths (containing 1 through n elements). How can I find the index of the objects with a length of 1?

I have tried:

lapply(list,function(x) x[which(length(x)==1)])

This correctly identifies the objects having a length of one, but does not give the numerical value representing their index within the list.

Upvotes: 1

Views: 1086

Answers (2)

Rich Scriven
Rich Scriven

Reputation: 99331

You can use the lengths() function to get the length of each element in the list, compare the result with 1 for the logical indices, then wrap with which() to get the numeric indices.

which(lengths(list) == 1)

Reproducible example:

set.seed(1)
(x <- replicate(3, sample(5, sample(3))))
# [[1]]
# [1] 5
#
# [[2]]
# [1] 4
#
# [[3]]
# [1] 1 3

which(lengths(x) == 1)
# [1] 1 2

Upvotes: 3

cptwonton
cptwonton

Reputation: 468

May have slight syntactic errors, but generally speaking this is what you can do:

#instantiate indexes vector here
list.length <- length(list)
for (i in 1:list.length) {
    if (length(list[i])==1) {
        indexes <- c(indexes, i)
    }
}

Upvotes: 0

Related Questions