Pull specific rows

此生再无相见时 提交于 2019-12-13 21:18:16

问题


Let's say that I have a data frame that looks like 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
     a          7
     a          8

Now I want to be able to pull the data for...

list <- c("x","y", "a")

And the desired out come would look something like this...

x  y a 
1  3 7 
2  4 8 

I tried using which(list%in%City) to help find the indices to pull that data from the index but that does not produce the rows that I want.

UPDATE

Make sure that when you are using Chris' answer that your data type for "City" is "chr" otherwise you will pop up with an error message as I got originally before using the "as.character" function.


回答1:


I renamed your variable list to test, because list is a function name. You can do this, using data.table:

matdt <- as.data.table(mat)
setkey(matdt, City)
sapply(test, function(x) matdt[x, Number])
     x y a
[1,] 1 3 7
[2,] 2 4 8



回答2:


You need to pass the City names to the extraction function one by one. In this case sapply will deliver a matrix as you expect but if there were a varying number of results per city, the retruned object would be a list rather than a matrix:

sapply( list, function(city) mat[ mat$City %in% city, "Number"] )
     x y a
[1,] 1 3 7
[2,] 2 4 8



回答3:


Using dplyr and tidyr:

mat %>%
  filter(City %in% c("x", "y", "a")) %>%
  group_by(City) %>%
  mutate(Index = 1:n()) %>%
  spread(City, Number) %>%
  select(-Index)


来源:https://stackoverflow.com/questions/31278008/pull-specific-rows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!