1

我正在尝试创建一个输出特定 sql 查询的 for 循环,该循环基于随每一步而变化的标准。此外,我正在尝试根据创建它们的步骤指定输出名称。例如,步骤 1 将输出一个名为 species1 的表。我尝试编写的代码如下。我确信答案很简单,但对于我的一生,我无法找到正确的表达方式。提前感谢您的所有帮助

for (i in 1:15) {
Species[i]<-sqldf("SELECT StartYear, StartMonthNo, RegionCode, CommonName, EstimatedBiomassg, ScaledProportionofDominantNektonBiomass
                FROM TrawlBiomassbyMonth
                WHERE CommonName = TopSpecies[i,1]
                AND RegionCode=1")

Species[i]TimeSeries<-sqldf("SELECT TimeSeries.StartYear, TimeSeries.StartMonthNo, CommonName, EstimatedBiomassg, ScaledProportionofDominantNektonBiomass
                FROM TimeSeries
                LEFT JOIN Species[i]
                ON TimeSeries.StartYear = Species1.StartYear 
                AND TimeSeries.StartMonthNo = Species1.StartMonthNo")
Species[i]TimeSeries[is.na(Species[i]TimeSeries)] <- 0}

编辑

这是一个简化的示例:

for (i in 1:2) {
  Species[i]<-sqldf("SELECT StartYear, StartMonthNo, CommonName, Biomass
                    FROM ExampleBiomass
                    WHERE CommonName = ExampleTopSpecies[i,1])}

生物质输出

structure(list(StartYear = c(1985L, 1985L, 1985L, 1985L, 1985L, 
1985L, 1985L, 1985L, 1985L, 1985L, 1985L, 1985L, 1986L, 1986L, 
1986L, 1986L, 1986L, 1986L, 1986L, 1986L, 1986L, 1986L, 1986L, 
1986L), StartMonthNo = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 
10L, 11L, 12L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 
12L), CommonName = structure(c(1L, 1L, 2L, 2L, 1L, 1L, 1L, 2L, 
2L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 2L, 2L
), .Label = c("Ninja", "Pirate"), class = "factor"), Biomass = c(26L, 
107L, 126L, 35L, 84L, 147L, 98L, 141L, 112L, 43L, 28L, 79L, 36L, 
126L, 31L, 89L, 133L, 34L, 38L, 117L, 92L, 81L, 93L, 127L)), .Names = c("StartYear", 
"StartMonthNo", "CommonName", "Biomass"), class = "data.frame", row.names = c(NA, 
-24L))

TopSpecies 的输入

structure(list(CommonName = structure(1:2, .Label = c("Ninja", 
"Pirate"), class = "factor"), Biomass = c(500L, 450L)), .Names = c("CommonName", 
"Biomass"), class = "data.frame", row.names = c(NA, -2L))
4

1 回答 1

1

你可以使用这样的东西:

basic_query <- "SELECT StartYear, StartMonthNo, CommonName, Biomass FROM ExampleBiomass WHERE CommonName = "

Species <- list()

for (i in 1:2) {
  Species[[i]] <- sqldf(paste(basic_query, as.character(ExampleTopSpecies[i,1])))
}

一些解释:

  • basic_query保存 SQL 查询的公共部分。
  • Species <- list()创建一个将由循环填充的空列表对象。
  • Species[[i]] <-向 list 添加一个元素Species
  • paste简单地连接字符串。
  • as.character(ExampleTopSpecies[i,1])是必需的,因为您的数据框包含因素。
于 2013-08-19T17:22:08.617 回答