Reputation: 3
df <- data.frame(name=c('aa', 'bb', 'cc','dd'),
code=seq(1:4), value= seq(100, 400, by=100))
df
v <- c(1, 2, 2)
v
A <- df[df$code %in% v,]$value
A
str(A)
I tried to obtain the corresponding value based on the code. I was expecting A
to be of length 3; but it actually returns a vector of 2. What can I do if I want A
to be a vector of 3, that is c(100,200,200)
?
Upvotes: 0
Views: 323
Reputation: 27388
%in%
returns a logical vector, the same length as vector 1, that indicates whether each element of vector 1 occurs in vector 2.
In contrast, the match
function returns, for each element of vector 1, the position in vector 2 where the element first appears (or NA
if it doesn't exist in vector 2). Try the following:
df[match(v, df$code), 'value']
Upvotes: 2
Reputation: 263301
You could just use v
as an argument if those were the lines whose "value"s you wanted:
> df[v,]$value
[1] 100 200 200
Upvotes: 0