简体   繁体   English

如何在R中的公式内循环

[英]How to loop within formulae in R

Here is the header of my data: 这是我的数据的标题:

Location    Aeration    Species   Form   Method  Repeat  Days   Act    Bac   COD    Fun NH3 NO2 NO3 TN  TP  SP  SS  ChlA    TDS Sal ODO

Now I want to commit aov analysis for each of the data from Act to ODO, which needs formula as an argument, such as Act~Species, if no loops is used, I have to type "Act ~ Species", "Bac ~ Species", "COD ~ Species"... so I wonder if there is some way to loop the data columns in the formulae, both for loops and apply family such as lapply are OK. 现在,我想对从Act到ODO的每个数据进行aov分析,这需要公式作为参数,例如Act〜Species,如果不使用循环,则必须键入“ Act〜Species”,“ Bac〜Species” “,” COD〜Species“ ...,所以我想知道是否有某种方法可以循环公式中的数据列,无论for循环还是诸如lapply类的apply系列都可以。 I've tried looping with indexes such as data[,8], data[8] and data[[8]] but it reported error. 我尝试使用诸如data [,8],data [8]和data [[8]]的索引进行循环,但报告错误。 Could anyone tell me how to loop within R formulae? 谁能告诉我如何在R公式内循环? And if there's any solution provided in Hadley Wickham's tidyverse package such as dplyr ? 如果Hadley Wickham的tidyverse软件包(例如dplyr提供了任何解决方案? Thanks in advance! 提前致谢!

Assuming your data are stored in a dataframe named df and that I counted correctly such that Act is col 8 and ODO is col 22: 假设您的数据存储在名为df的数据帧中,并且我计数正确,因此Act为col 8, ODO为col 22:

res_list <- vector(mode="list", length=105)
r <- 1
for (i in 8:22) {
for (j in 8:22) {
    if(i>j) {
        res_list[[r]] <- aov(as.formula(paste(names(df)[i], "~", names(df)[j])), data=df)
        r <- r+1
    }
}
}

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

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