根据名称选择列表元素 [英] Select list element based on their name
本文介绍了根据名称选择列表元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个向量的命名列表,这些向量表示源自两个样本"A"和"B"的事件:
I have a named list of vectors that represent events originated from 2 samples, "A" and "B":
l.temp <- list(
SF1_t_A = c(rep(1:10)),
SF2_t_A = c(rep(9:15)),
SF1_t_B = c(rep(8:12)))
l.temp
$SF1_t_A
[1] 1 2 3 4 5 6 7 8 9 10
$SF2_t_A
[1] 9 10 11 12 13 14 15
$SF1_t_B
[1] 8 9 10 11 12
现在,我只想从样本"A"或"B"中选择列表中的元素.我可以通过循环来完成它,但是当plyr在身边时,这种使用方式就违背了使用list的观点.到目前为止,这是我尝试过的方法:
Now I want select only the elements of the list that are either from sample "A" or "B". I could go about doing it with a loop but that sort of defies the point of using list when plyr is around. This, and variations, is what I've tried so far:
llply(l.temp , function(l){
if ((unlist(strsplit(names(l), "_"))[3]) == "A"){
return(l)}
})
这是我得到的错误:
Error in unlist(strsplit(names(l), "_")) :
error in evaluating the argument 'x' in selecting a method for function 'unlist':
Error in strsplit(names(l), "_") : non-character argument
感谢我对我做错事的帮助.
Help on what I am doing wrong is appreciated.
推荐答案
您可以在列表名称中找到模式,从而为您提供其中一个的索引:
You can find the pattern in the names of the list, which gives you an index of which ones:
grep("_A$", names(l.temp))
然后将其用于子集:
l.temp[grep("_A$", names(l.temp))]
这篇关于根据名称选择列表元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文