[R] ask a question about list in R project

Joshua Wiley jwiley.psych at gmail.com
Tue Jun 29 08:29:27 CEST 2010


Hello,

It looks to me like you want all the values of 'mylist' returned in a
list except for a[i] for each element of a.  In this case, length(a) =
4, so you want 4 lists.  If this is not what you were trying to do,
perhaps you could explain the pattern between your data and your
desired output.

####################
a <- c(2,3,5,7)
mylist <- list(c(2,3),5,7)

#Option 1
#Returns a list with 4 elements each of which is itself a list
lapply(a, function(y) {lapply(mylist, function(x) {x[x!=y]})})

#Option 2
#Prints 4 lists, but uses a for loop, and does not save nicely
for(i in seq_along(a)) {print(lapply(mylist, function(x) {x[x!=a[i]]}))}

####################

As a side note, including ' rm(list=ls()) ' in example code is often
discouraged.  If someone just copied and pasted all the code into the
console work could be lost.

Best regards,

Josh

On Mon, Jun 28, 2010 at 10:09 PM, song song <rprojecthelp at gmail.com> wrote:
> I found this loop can do this. is there any simple method?
>
> rm(list=ls())
> a=c(2,3,5,7)
> mylist=list(c(2,3),5,7)
>
> newlist=list()
> for (i in 1:4){
>  for (j in 1:length(mylist)){
>     newlist[[j]]=mylist[[j]]
>     if (a[i] %in% mylist[[j]]){
>        newlist[[j]]=mylist[[j]][mylist[[j]]!=a[i]]
>        if (length(newlist[[j]])==0){
>           newlist[[j]]=NA
>        }
>     }
>  }
>  print(newlist[!is.na(newlist)])
> }
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



-- 
Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles
http://www.joshuawiley.com/



More information about the R-help mailing list