jlopez
jlopez

Reputation: 347

Indexing data.frame from vector in R

I have a very simple indexing question. If I have two variables A and B

A = c(1,2,1,1) 
B = data.frame( x = c(1,2), y=c( 'up', 'down') ) 

I need to have a output of A that results like

[1] "up" "down" "up" "up"

My code is this

 B[ which(A %in% B$x), ]$y

But I get

[1] "up" "down" NA NA

Which is the shortest way to fix my code?

Upvotes: 0

Views: 1126

Answers (2)

Gregor Thomas
Gregor Thomas

Reputation: 145745

Two ways to think about this:

You want the A-indexed elements of the y column of B - so extract the y column with $ and apply the index A with [.

B$y[A]

Or, you want the A-indexed rows of B, and you only care about the y column, use the standard data frame indexing of data[rows, columns]:

B[A, "y"]

Upvotes: 1

Clemsang
Clemsang

Reputation: 5481

You can use named vectors:

unname(c("1" = "up", "2" = "down")[A])
[1] "up"   "down" "up"   "up" 

Upvotes: 0

Related Questions