catmandoes catmandoes - 24 days ago 8
R Question

R: string vector, finding values of indeices smaller than a certain number

could anyone kindly help me with the error message below?

list <- c("apple","bee","cat","dog","egg","frog","goat","hippo","iguana")

list[1:5]
# [1] "apple" "bee" "cat" "dog" "egg"


However,

list[<5]
# Error: unexpected '<' in "list[<"


Thank you.

Answer

We need either a numeric index (in the OP's first example) or logical index to subset the 'list'. To create a logical index, we can compare the sequence of 'list' elements with the index 5.

seq_along(list)<5
#[1]  TRUE  TRUE  TRUE  TRUE FALSE FALSE FALSE FALSE FALSE

and using this index, we can get the elements that corresponds to TRUE values

list[seq_along(list)<5]
#[1] "apple" "bee"   "cat"   "dog"  

Regarding the error message, if we type

<5

on the console

Error: unexpected '<' in "<"

So, it needs a value on the lhs of <

Comments