On 14-03-17 7:27 AM, sylvain willart wrote:
Dear R (list)-users
I'm trying to extract part of a list based on the value of one of the
subsubscript element
As those things are usually quite complicated to explain, let me provide a
simple reproducible example that closely matches my problem (although my
actual list has a few thousands elements):
###### EXAMPLE
MyFullList<-list()
v1<-rep(c("A","B","C","D","E"),2)
v2<-c(rep(1,5),rep(2,5))
for (i in 1:10){
MyFullList[[i]]<-density(runif(10,0,1))
MyFullList[[i]][8]<-i
MyFullList[[i]][9]<-v1[i]
MyFullList[[i]][10]<-v2[i]
}
###### end example
Now, my problem is that I would like to extract, in a new list, a part of
the full list based on the value of it's 9th subscript, let say, "B". This
new list has to include S3-densities objects (stored in the first 7
sub-elements)
You'll need to do this in two steps, you can't do it using only
indexing. The problem is that logical indexing requires a logical
vector, and it's not easy to get one of those when you are starting with
a list. So here's how to do it:
First create a new character vector containing the 9th subscript of each
element, e.g.
ninths <- sapply(MyFullList, function(x) x[[9]])
You use sapply so that the result is coerced to a character vector, and
x[[9]] rather than x[9] so that each result is a scalar character.
Do your test on that, and use the result to index the full list:
MyFullList[ninths == "B"]
This returns a list containing the cases where the test evaluates to TRUE.
Duncan Murdoch
Here's what I tried (and the errors I got)
####### TRIALS
MyList_v1_B<-MyFullList[MyFullList[[]][9]=="B"]
# error invalid subscript type 'symbol'
MyList_v1_B<-MyFullList[MyFullList[][9]=="B"]
# no errors, but returns an empty list ???
MyList_v1_B<-MyFullList[MyFullList[,9]=="B"]
# error incorrect number of dimensions
######## end trials (for now)
Obviously, I'm missing something,
And I would appreciate any clue to help me perform this task
# Here is my R.version info, although I'm not sure it's relevant here
R.version
platform x86_64-unknown-linux-gnu
arch x86_64
os linux-gnu
system x86_64, linux-gnu
status
major 2
minor 15.2
year 2012
month 10
day 26
svn rev 61015
language R
version.string R version 2.15.2 (2012-10-26)
nickname Trick or Treat
thanks
Sylvain Willart
[[alternative HTML version deleted]]
______________________________________________
R-help@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.
______________________________________________
R-help@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.