aqkhan
aqkhan

Reputation: 86

Running Correlation in a For loop in R

I am trying to run a correlation in R in a for loop for about 14 data frames. The code works outside the for loop (without the concatenation) but not in the for loop.Gives me the error "non-numeric argument to binary operator"

Image showing one of the data frames in the for loop that the correlation is being run on

#for loop to go through each crime type

    y<- unique(crimeSummary$cType) #To get the types of crime that I am trying to the run the corr on. 
    for(i in 1:length(y)){
      cor.test(paste("mergedpoW"+y+"$total.x", sep = "."), paste("mergedpoW"+y+"$total.y",sep = "."))
    }

Upvotes: 0

Views: 378

Answers (1)

lefft
lefft

Reputation: 2105

You can use eval(parse()) to evaluate strings as code. For example:

y <- unique(iris$Species) 
species_means <- rep(NA, 3)
for(i in 1:length(y)){
  string <- paste0("mean(iris$Sepal.Length[iris$Species=='", y[i], "'])")
  print(string)
  species_means[i] <- eval(parse(text=string))
}
print(species_means)

And a couple of quick points:

  • You can't use + for string concatenation in (base) R. So in your case, replace the +s with commas -- paste("mergedpoW", y, "$total.x", sep = ".") (btw, should sep be ""? in the example?)

  • There's easier/cleaner ways to summarize multiple data frames -- e.g. you can collect all the df's into a list, and then use lapply(df_list, your_summary_function)

Hope this helps!

Upvotes: 1

Related Questions