Doran, Harold wrote:

Dear List:

I am generating N datasets using the following

Sigma<-matrix(c(400,80,80,80,80,400,80,80,80,80,400,80,80,80,80,400),4,4
)
mu<-c(100,150,200,250)

N=100
for(i in 1:N) { assign(paste("Data.", i, sep=''),
as.data.frame(cbind(seq(1:1000),(mvrnorm(n=1000, mu, Sigma)))))
}


With these datasets, I need to work on some of the variables and then
run each dataset through a linear model. I am having some trouble
working with variables within the loop and wonder if anyone can offer
any pointers.


The first thing I am trying to do is add 2 variables together that are
in each dataset. I am sure this is extremely trivial, but I can't seem
to get that to work.

I have tried:

for (i in 1:5){
assign(paste("x",i,sep=""),(get(paste("Data.",i,sep=""))[["V2"]])+(get(p
aste("Data.",i,sep=""))[["V2"]]))
}

It's time to forget those 100 separate R objects, but try to work with a list, which makes life worth living again. ;-)


I'm reusing most of your code:

  Sigma <- matrix(
    c(400,80,80,80,80,400,80,80,80,80,400,80,80,80,80,400),
    4, 4)
  mu <- c(100,150,200,250)
  N <- 100

  Data <- lapply(seq(N), function(x)
    as.data.frame(cbind(1:1000, mvrnorm(n=1000, mu, Sigma))))

  # so we have a list Data with 100 elements,
  # each containing a data.frame.

  for(i in seq(along=Data))
    Data[[i]]$V6 <- Data[[i]]$V1 + Data[[i]]$V2


Uwe Ligges



Now, this code works, but I want for this vector to be a variable within
each dataframe. Outside the loop, the equivalent code would be

attach(Data.1)
Data.1$V6<-V1+V2
Detach(Data.1)

Another task I would like to perform is to reshape each dataframe for
longitudinal analysis. I have tried the following:

for (i in 1:5){
assign(paste("long",i,sep=""),reshape(paste("Data.",i,sep=""),idvar=get(
paste("Data.",i,sep="")[["V1"]]),
varying=list(names(get(paste("Data",i,sep="")[["V2"]]):get(paste("Data",
i,sep="")[["V5"]])),v.names="score",direction="long")
}


This isn't working and I'm not sure if the code is even close.

In general, performing all of these operations outside a loop for a
single dataframe is simple. My trouble is performing equivalent
operations within a loop.


Thanks for any help offered.

Harold

        [[alternative HTML version deleted]]

______________________________________________
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

______________________________________________ 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

Reply via email to