【问题标题】:Running Correlation in a For loop in R在 R 的 For 循环中运行相关性
【发布时间】:2018-06-28 06:50:54
【问题描述】:

我正在尝试在 R 中为大约 14 个数据帧在 for 循环中运行相关性。代码在 for 循环之外工作(没有连接),但不在 for 循环中。给我错误 "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 = "."))
    }

【问题讨论】:

    标签: r statistics data-science


    【解决方案1】:

    您可以使用eval(parse()) 将字符串评估为代码。例如:

    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)
    

    还有几个要点:

    • 您不能使用+ 在(基本)R 中进行字符串连接。因此,在您的情况下,将+s 替换为逗号——paste("mergedpoW", y, "$total.x", sep = ".")(顺便说一句,sep 应该是@ 987654327@? 在例子中?)

    • 有更简单/更简洁的方法来汇总多个数据帧——例如您可以将所有df收集到一个列表中,然后使用lapply(df_list, your_summary_function)

    希望这会有所帮助!

    【讨论】:

    • 嗨,谢谢,不知道“species_means
    • 我最近的样子如下 y
    • species_means &lt;- rep(NA, 3) 只是创建一个空向量来捕获结果(每个插槽都由species_means[i] &lt;- ... 填充)。所以当循环完成时,你想要的值将在species_means
    猜你喜欢
    • 2016-11-14
    • 2018-07-22
    • 2011-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-28
    • 2020-08-31
    相关资源
    最近更新 更多