[R] Ignoring missing elements in data.frame()

Joris Meys jorismeys at gmail.com
Sat Jun 5 23:22:51 CEST 2010


Hi,

One possible way to get around it is using following idea :
X1 <- rnorm(10)
X2 <- rnorm(10)

Names <- c("X1","X2","X3")
Names <- Names[Names %in% ls()]

n <- length(Names)
p <- 10   #length of each object
output <- matrix(NA,ncol=n,nrow=p)

for(i in 1:n){
    output[,i] <- get(Names[i])
}
output <- as.data.frame(output)
names(output) <- Names

You can also use an eval-parse construct like this :
## Alternative
Names <- c("X1","X2","X3")
Names <- Names[Names %in% ls()]
Names <- paste(Names,collapse=",")
expr = paste("output <- data.frame(",Names,")",sep="")
eval(parse(text=expr))

Both are not really the most optimal solution, but do work. It would
be better if you made a list or matrix beforehand and then save the
results of the calculations in that list or matrix whenever the
calculation turns out to give a result.

Cheers
Joris

On Sat, Jun 5, 2010 at 1:23 AM, Scott Chamberlain <schamber at rice.edu> wrote:
> Hello, I am trying to make a data frame from many elements after
> running a function which creates many elements, some of which may not
> end up being real elements due to errors or missing data. For example,
> I have the following three elements p1s, p2s, and p3s. p9s did not
> generate the same data as there was an error in the function for some
> reason. I currently have to delete p9s from the data.frame() command
> to get the data.frame to work.  How can I make a data frame by somehow
> ignoring elements (e.g., p9s) that do not exist, without having to
> delete each missing element from data.frame()? The below is an example
> of the code.
>
>> p1s
>      statistic parameter p.value
> [1,] 3.606518  153       0.0004195377
>> p2s
>      statistic parameter p.value
> [1,] -3.412436 8         0.009190015
>> p3s
>      statistic parameter p.value
> [1,] 1.543685  599       0.1231928
>
>> t(data.frame(t(p1s),t(p2s),t(p3s),t(p9s)))
> Error in t(p9s) : object 'p9s' not found
>
>
> Thanks, Scott Chamberlain
> Rice University
> Houston, TX
>
> ______________________________________________
> 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.
>



-- 
Ghent University
Faculty of Bioscience Engineering
Department of Applied mathematics, biometrics and process control

tel : +32 9 264 59 87
Joris.Meys at Ugent.be
-------------------------------
Disclaimer : http://helpdesk.ugent.be/e-maildisclaimer.php



More information about the R-help mailing list