[英]subset dataframe based on rownames
I have two data frames ( bwenv
and bwsp
). 我有两个数据帧(
bwenv
和bwsp
)。 bwsp
is a subset of bwenv
and they have matching rownames (sample id). bwsp
的一个子集bwenv
并且它们具有匹配rownames(试样ID)。 I would like to subset bwenv
so that it only includes the rows that are also found in bwsp
. 我想对
bwenv
进行子集bwenv
,使其仅包括在bwsp
中也可以找到的行。
When the number of rows match, I have used: 当行数匹配时,我使用了:
bw2015 <- cbind(bwenv, bwsp)
bw2015 <-cbind(bwenv,bwsp)
to create a new dataframe with the combined data. 使用合并的数据创建一个新的数据框。
My question is very similar to the question asked here: R subset a column in data frame based on another data frame/list , but the subsetting is done by a column of data in each dataframe (rather than row names like I want to do). 我的问题与此处提出的问题非常相似: R基于另一个数据帧/列表在数据帧中对列进行子集设置 ,但子集由每个数据帧中的数据列完成(而不是像我想做的行名) 。
library(dplyr)
bw2015 <- bwenv %>%
add_rownames("row_names") %>%
semi_join(add_rownames(bwsp, "row_names"), by = "row_names")
Following on from @yeedle's solution, I modified it a little and found this worked for me: 在@yeedle的解决方案之后,我对其进行了一些修改,发现这对我有用:
library(dplyr)
bwenv2 <- bwenv %>%
rownames_to_column("row_names") %>%
semi_join(rownames_to_column(bwsp, "row_names"), by = "row_names")
rownames(bwenv2) <- bwenv2$row_names
bwenv2 <- bwenv2 %>% select(-row_names)
bw2015 <- cbind(bwenv2, bwsp)
str(bw2015)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.