开发者

Selecting and separating elements from a list

I have a list of names in a list, such as:

site <- list("site2-site22" ,"site2-site45", 开发者_开发问答"site4-site2", 
             "site6-site2","site9-site4", "site20-site6", 
             "site25-site272", "site32-site47","site62-site74", 
             "site272-site280")

From the list, for example, I need to select those elements which has site2 in it, either before or after -

and put them in a separate list,

I can use grep command as below:

grep("^site2-|-site2$",site,value=T)

and save them all in a separate list.

In a similar way I need to select for all other sites: site2, site3, site4, etc. and save them in a separate list for each site, but is there a way with a single command to separate them and save each in different lists?


Have you considered using the functions paste and lapply to build the string pattern to match against and then apply grep over each site? Something like this:

site <- list("site2-site22" ,"site2-site45", "site4-site2", 
             "site6-site2","site9-site4", "site20-site6", 
             "site25-site272", "site32-site47","site62-site74", 
             "site272-site280")

l <- paste("site",c(2,4,6),sep="")

myFun <- function(x,siteList){
    pat <- paste("^",x,"-|-",x,"$",sep="")
    grep(pat,siteList,value = TRUE)
}

lapply(l,FUN = myFun, siteList = site)

which returns this:

[[1]] [1] "site2-site22" "site2-site45" "site4-site2"  "site6-site2" 

[[2]] [1] "site4-site2" "site9-site4"

[[3]] [1] "site6-site2"  "site20-site6"


First, make a vector of all the possible sites, if you don't already have that. I give the site its own name to make things better labeled later.

sites <- unique(unlist(strsplit(unlist(site), "-")))
names(sites) <- sites

Then you can use the plyr library to loop over this and run the grep for each site, building the grep string using paste.

library("plyr")

llply(sites, function(s) {grep(paste("^",s,"-|-",s,"$",sep=""), site, value=TRUE)})


Well, I don't know of a single command, but a single line could be:

lapply(1:5, function(i) grep(paste("^site",i,"-|-site",i,"$", sep=""),site,value=T))

...and then of course modify the 1:5 to suit your needs.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜