Reputation: 1
I want to be able to run the same functions repeatedly, across a suite of paired variables. I have read other posts, and they suggest using the lapply function to do such a process, but I cannot get that to work in this case, likely because of my limited understanding of how to implement the appropriate "apply".
Here's the code I have. You can see that it properly creates the text to run the functions (held in formulas.ccf and formulas.lagplot) and the proper variable for assignment (held in varnames), but how do I implement the functions and assign them to the appropriate varname?
names <- c("aran", "galv", "cc", "sa") #Names of the data vectors
cntr=1
varname <- array("",dim=c(9))
formulas.ccf <- array("",dim=c(9))
formulas.lagplot <- array("",dim=c(9))
for (i in 1:3){
for (j in 2:4) {
varname[cntr] <- paste("ccf",names[i],names[j],sep="_")
formulas.ccf[cntr] <- paste("ccf(mydata$",names[i],", mydata$",names[j],",na.action=na.pass)",sep="")
formulas.lagplot[cntr] <- paste("lagplot2(mydata$",names[i],", mydata$",names[j],",15)",sep="")
cntr<-cntr+1
}
}
varname
formulas.ccf
formulas.lagplot
Here one set of the code I wish to run; for this example varname="ccf_aran_galv", the ccf function="ccf(mydata$aran, mydata$galv,na.action=na.pass)" and the lagplot function="lag.plot2(mydata$aran_perc, mydata$galv_perc, 15)". This code would be run 9 times, once for each pair of variables:
ccf_aran_galv <- ccf(mydata$aran, mydata$galv,na.action=na.pass)
lag.plot2(mydata$aran_perc, mydata$galv_perc, 15)
I'm stuck, so would appreciate anyone's help. I can obviously write out this code repeatedly, but would like to have a smaller coding footprint and increased flexibility.
Thanks
Upvotes: 0
Views: 186
Reputation: 173517
I'm going to try to point you in the right direction, even though your example isn't totally reproducible.
If you're building R code as character strings with the hopes of then executing it, that is a big big sign that you're doing it wrong. There are times when it's necessary, but they are rare.
Another warning bell here is your fixation on $
. There are other (better) ways of referring to the columns of data frames: [
and [[
. See ?Extract
. For instance, let's just look at the series of ccf
calls you're trying to execute here. This would be a simple way of doing that:
#Assuming that mydata is a data frame with 4 columns
# named "aran", "galv", "cc", "sa".
results <- vector("list",9)
nm <- c("aran", "galv", "cc", "sa")
counter <- 1
for (i in 1:3){
for (j in 2:4){
results[[counter]] <- ccf(mydata[,nm[i]],mydata[,nm[j]],na.action = na.pass)
counter <- counter + 1
}
}
Note that I'm following your lead and indexing the columns of mydata
my character by referring to a particular element in the vector nm
. (I didn't call it names
because that's a very common function.) But you could just as easily indexed them directly by position using i
and j
directly, assuming the columns are in the order you want.
Upvotes: 3