[英]Subsetting a dataframe according to a list of vectors
我有一個字符向量列表,稱為l
。 例如:
set.seed(42) ## for sake of reproducibility
genes <- paste("gene",1:20,sep="")
tot=data.frame(term=sample(genes,30, replace=T), num=sample(1:10, 30, replace=T), stringsAsFactors =
FALSE)
s1<-sample(genes,2, replace=F)
s2<-sample(genes,4, replace=F)
s3<-sample(genes,3, replace=F)
s4<-sample(genes,2, replace=F)
s5<-sample(genes,2, replace=F)
s6<-sample(genes,3, replace=F)
l=list(s1,s2,s3,s4,s5,s6)
通過考慮tot[tot$term%in%l[[1]],]
,我得到:
term num
1 gene17 4
3 gene1 6
7 gene17 2
26 gene1 6
我把
df=tot[tot$term%in%l[[1]],]
sum(df$num)
我可以獲得第二列的總值,即18。對於我獲得的列表的其他元素,分別為: 32 13 19 17 29
。 這可以通過 for 循環來實現:
v<-vector()
for (j in 1:length(l)) {
df=tot[tot$term%in%l[[j]],]
v<-c(v,sum(df$num))
}
我想知道是否有更簡單的方法可以做到這一點。
可以用sapply
簡化
v2 <- sapply(l, function(j) sum(tot$num[tot$term %in% j]))
-檢查 OP 的循環 output
identical(v, v2)
#[1] TRUE
或者更緊湊的方式map
library(purrr)
map_dbl(l, ~ sum(tot$num[tot$term %in% .x]))
或者使用tidyverse
library(dplyr)
stack(setNames(l, seq_along(l))) %>%
group_by(ind) %>%
summarise(Sum = tot %>%
filter(term %in% values) %>%
pull(num) %>%
sum) %>%
pull(Sum)
這是一種tidyverse
方式:
library(tidyverse)
enframe(l, value = 'term') %>%
unnest(term) %>%
left_join(tot, by = 'term') %>%
group_by(name) %>%
summarise(num = sum(num, na.rm = TRUE))
# name num
#* <int> <int>
#1 1 18
#2 2 32
#3 3 13
#4 4 19
#5 5 17
#6 6 29
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.