简体   繁体   中英

Selecting at most n elements in R

It seems like a very simple question, but I can't figure it out.

How can I select at most n elements from a list in R?

> x = 1:3
> x[1:5]
[1]  1  2  3 NA NA

What I want is that x[1:5] return [1] 1 2 3 .

My attempted solution is

x[!is.na(x[1:3])]

which still doesn't work, because

> x[!is.na(x[1:5])]
[1] 1 2 3            # correct
> x[!is.na(x[1:2])]
[1] 1 2 3            # where's that coming from?

为了确保您不索引向量的结尾,您可以执行以下操作:

x[1:(min(5, length(x)))]

x[!is.na(x[1:2])]
[1] 1 2 3 # where's that coming from?

That's coming from recycling .
is.na(X) returns a logical vector of length equal to its argument X . Since there are no NA s this vector is all TRUE s. Those values (again, all TRUE ) are recycled to the length of x (the x on the outside of the brackets, x[ . ] )

As for taking a selection from x, not to exceed the length of x, use head and tail as @Ananda mentioned in the comments.

x <- 1:6
head(x, 4)
# [1] 1 2 3 4
head(x, 20)
# [1] 1 2 3 4 5 6

tail(x, 4)
# [1] 3 4 5 6
tail(x, 20)
# [1] 1 2 3 4 5 6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM