r - Pull specific rows -
let's have data frame looks this...
city <- c("x","x","y","y","z","z","a","a") number <-c(1,2,3,4,5,6,7,8) mat <- cbind.data.frame(city ,number) "city" "number" x 1 x 2 y 3 y 4 z 5 z 6 7 8
now want able pull data for...
list <- c("x","y", "a")
and desired out come this...
x y 1 3 7 2 4 8
i tried using which(list%in%city) find indices pull data index not produce rows want.
update
make sure when using chris' answer data type "city" "chr" otherwise pop error message got before using "as.character" function.
i renamed variable list
test
, because list
function name. can this, using data.table
:
matdt <- as.data.table(mat) setkey(matdt, city) sapply(test, function(x) matdt[x, number]) x y [1,] 1 3 7 [2,] 2 4 8
Comments
Post a Comment