What is being returned from the 'sapply' is a 'list' and to
process the
information in the list, you should use 'lapply'. I assume that you
want to
keep 's' around for further processing. Here is a simple example that
makes
every other entry in the list a NULL and then uses 'lapply' to iterate
through the list. So you have in the return object ('s') a list of
return
values.
> x <- sapply(1:10, function(z) if ((z %% 2) == 0) list(a=1:3,b=3) else
NULL)> str(x)
List of 10
$ : NULL
$ :List of 2
..$ a: int [1:3] 1 2 3
..$ b: num 3
$ : NULL
$ :List of 2
..$ a: int [1:3] 1 2 3
..$ b: num 3
$ : NULL
$ :List of 2
..$ a: int [1:3] 1 2 3
..$ b: num 3
$ : NULL
$ :List of 2
..$ a: int [1:3] 1 2 3
..$ b: num 3
$ : NULL
$ :List of 2
..$ a: int [1:3] 1 2 3
..$ b: num 3> # to process non-NULL data
> lapply(x, function(z) if (is.null(z)) print("NULL") else
print("non-NULL"))
[1] "NULL"
[1] "non-NULL"
[1] "NULL"
[1] "non-NULL"
[1] "NULL"
[1] "non-NULL"
[1] "NULL"
[1] "non-NULL"
[1] "NULL"
[1] "non-NULL"> # can also use a 'for' loop
> for (i in x) if (is.null(i)) print("NULL") else
print("non-NULL")
[1] "NULL"
[1] "non-NULL"
[1] "NULL"
[1] "non-NULL"
[1] "NULL"
[1] "non-NULL"
[1] "NULL"
[1] "non-NULL"
[1] "NULL"
[1] "non-NULL">
>
On 2/15/07, Antje <niederlein-rstat@yahoo.de>
wrote:>
> Hello,
>
> I have some problems with sapply. I wanted to do the following:
>
> s <- sapply(filelist, function(x) {
> if(file.exists(x))
> {
> ...
> return( list(density(file$V1)$x,
> density(file$V1)$y))
> }
> else
> {
> print(paste("plotDensity ERROR - File does not
> exist: ",x,sep=""))
> return( NULL)
> }
> })
>
> if(is.null( - ??? - ))
> {
> print("no plot")
> }
>
> That means, I try to read every file and to get some data from it. It
> may happen, that the file does not exist and then I don't want to plot
> anything. As return, I get a list and I have quite a lot of problems to
> access its content... (I did not really understand how this works, I
> guess...)
> Could anybody give me a hint?
>
> Thank you!
> Antje
>
> ______________________________________________
> R-help@stat.math.ethz.ch 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.
>
--
Jim Holtman
Cincinnati, OH
+1 513 646 9390
What is the problem you are trying to solve?
[[alternative HTML version deleted]]