Home Ask Login Register

Developers Planet

Your answer is one click away!

cfosser February 2016

How to select rows from a data frame with replacement

I have a data frame defined as follows:

t1 <- data.frame(x=c("A","B","C"),y=c(5,7,9))

> t1
  x y
1 A 5
2 B 7
3 C 9

and a vector of picks:

picks <- c("B","C","B")

How do I get these rows, with replacement, in this order selected from the data frame? I want:

x  y
B  7
C  9
B  7

I tried

> t1[t1$x %in% picks,]

  x y
2 B 7
3 C 9

and several other combinations of match, grep, which, etc and cannot get out what I want. It seems like it should be easy but I'm not finding the path.


mtoto February 2016

Or you can perform an right join using data.table

picks <- data.table(x = picks)
setDT(t1)[picks, on = "x"]
#   x y
#1: B 7
#2: C 9
#3: B 7

By default the merged data.table is sorted according to x in picks.

akrun February 2016

We can also use

setNames(t1$y, t1$x)[picks]
#B C B 
#7 9 7 

Post Status

Asked in February 2016
Viewed 3,913 times
Voted 12
Answered 2 times


Leave an answer

Quote of the day: live life