简体   繁体   English

在R中的For循环中运行相关

[英]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. 我正在尝试在for循环中的R中运行相关性,以获取大约14个数据帧。 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" 该代码在for循环外(没有串联)工作,但在for循环中工作。给我错误“二进制运算符的非数字参数”

Image showing one of the data frames in the for loop that the correlation is being run on 该图显示了正在运行关联的for循环中的数据帧之一

#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 = "."))
    }

You can use eval(parse()) to evaluate strings as code. 您可以使用eval(parse())将字符串作为代码求值。 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?) 您不能在(base)R中使用+进行字符串连接。因此,在您的情况下,用逗号替换+ s- paste("mergedpoW", y, "$total.x", sep = ".") (顺便说一句,在示例中sep应该是""吗?)

  • There's easier/cleaner ways to summarize multiple data frames -- eg you can collect all the df's into a list, and then use lapply(df_list, your_summary_function) 有比较简单的方法来汇总多个数据帧-例如,您可以将所有df收集到一个列表中,然后使用lapply(df_list, your_summary_function)

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM