Question

I am analyzing degradation of certain substances over time. Goal of the script is to get a list containing the variance of the observations at a certain time after application ("Dag" variable).

Output of the script below is a list containing NULL values. I think the problem lies with my assignment of the variable aux1 to the list item but the line works when I do it via command line.

There is probably a faster way of calculating this; even after 2 months I still feel overwhelmed by R.

mydata1<-as.data.frame(matrix(rnorm(600),ncol=6))
names(mydata1)=c("a","b","c","d","e","f")
substance1<-names(mydata1)
times1<-as.data.frame(rep(seq_len(10),10),ncol=1)
names(times1)<-"Dag"
times2<-unique(times1)
mydata1<-cbind(times1,mydata1)

vartijd<-function(times,mydata,substance){
  varlist<<-vector("list",length(substance))
  for (j in 1:length(substance))
    aux<-sapply(times,function(i)var(mydata[mydata$Dag==i,substance[j]],na.rm=TRUE))
    aux1<-cbind(times,aux)
  varlist[[j]]<-aux1

}
vartijd(times2,mydata1,substance1)
Was it helpful?

Solution

With basic fixes to your code, this works fine.

vartijd<-function(times,mydata,substance){
  varlist<-vector("list",length(substance)) # local `<-` assignment
  for (j in 1:length(substance)){ # opening bracket
    aux<-sapply(times,function(i)var(mydata[mydata$Dag==i,substance[j]],na.rm=TRUE))
    aux1<-cbind(times,aux)
    varlist[[j]]<-aux1
  } # closing bracket
  return(varlist) # explicit return
}

Result:

> out <- vartijd(times2,mydata1,substance1)
> str(out)
List of 6
 $ :'data.frame':       10 obs. of  2 variables:
  ..$ Dag: int [1:10] 1 2 3 4 5 6 7 8 9 10
  ..$ aux: num [1:10] 0.997 0.997 0.997 0.997 0.997 ...
 $ :'data.frame':       10 obs. of  2 variables:
  ..$ Dag: int [1:10] 1 2 3 4 5 6 7 8 9 10
  ..$ aux: num [1:10] 0.891 0.891 0.891 0.891 0.891 ...
 $ :'data.frame':       10 obs. of  2 variables:
  ..$ Dag: int [1:10] 1 2 3 4 5 6 7 8 9 10
  ..$ aux: num [1:10] 1.08 1.08 1.08 1.08 1.08 ...
 $ :'data.frame':       10 obs. of  2 variables:
  ..$ Dag: int [1:10] 1 2 3 4 5 6 7 8 9 10
  ..$ aux: num [1:10] 0.927 0.927 0.927 0.927 0.927 ...
 $ :'data.frame':       10 obs. of  2 variables:
  ..$ Dag: int [1:10] 1 2 3 4 5 6 7 8 9 10
  ..$ aux: num [1:10] 0.86 0.86 0.86 0.86 0.86 ...
 $ :'data.frame':       10 obs. of  2 variables:
  ..$ Dag: int [1:10] 1 2 3 4 5 6 7 8 9 10
  ..$ aux: num [1:10] 0.874 0.874 0.874 0.874 0.874 ...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top