如何在for循环中使用fn $

时间:2015-02-25 15:51:38

标签: r for-loop sqldf

我无法在for循环中使用fn $。当我用一个变量(x =“a_ind”)测试它时,我能够成功运行一个循环。但是,当我通过(c(“a_ind”,...))添加多个变量时,它不再起作用。我无法在线或在论坛上找到解决方案

请帮忙!

library("sqldf")
library("gsubfn")

df <- data.frame( a_ind = c("1","0","0","0"),
            b_ind = c("0","1","0","0"),
            c_ind = c("0","0","1","0"),
            d_ind = c("0","0","0","1"),
            var1  = c(11,22,33,44),
            var2  = c(50,30,75,100))


    x <- c("a_ind","b_ind","c_ind","d_ind")
    for (i in x){

    product <- fn$sqldf('
                select 
                    $x,
                    var1 * var2 as var3
                from df
                where $x = "1" ')

    product <- rbind(product,product)
    product <- product[!duplicated(product),]
    }

    View(product)

结果  在: sqliteSendQuery(con,statement,bind.data)中的错误:   声明中的错误:没有这样的功能:c

所需的输出如下所示:

name  var3
a_ind 550
b_ind 660
c_ind 2475
d_ind 4400 

1 个答案:

答案 0 :(得分:1)

我想在得到MrFlick和G. Grothendieck的帮助后结束这个问题。在for循环(i in x)中,在代码中使用“i”。这得到了所需的输出。包括的附加步骤是创建一个空的数据集“new”,以便我的rbind可以有一些东西来添加数据。

感谢所有帮助人员

library("sqldf")

new = data.frame(matrix(vector(),0,2,
               dimnames=list(c(),
             c("name","var3"))),
             stringsAsFactors=F)


df <- data.frame( a_ind = c("1","0","0","0"),
            b_ind = c("0","1","0","0"),
            c_ind = c("0","0","1","0"),
            d_ind = c("0","0","0","1"),
            var1  = c(11,22,33,44),
            var2  = c(50,30,75,100))

x <- c("a_ind","b_ind","c_ind","d_ind")
for (i in x){

product <- fn$sqldf('
           select 
                $i,
                var1 * var2 as var3
            from df
            where $i = "1" ')

new <- rbind.fill(new,product)
new<- new[!duplicated(new),]
}

View(new)