如果我在一个循环中多次调用Quantile,我可以保存到DataFrame吗?

时间:2015-02-18 20:11:20

标签: r

我有一个sql statments的数据框z 即从表中选择年龄= state =' fl',    从表中选择年龄,其中state =' ny'等

然后我循环通过数据帧运行每个查询然后运行输出 分位数fct为我写入文件的每个查询获得百分位数

有没有办法将分位数输出保存到数据帧???

由于

for (x in z) {
     dflist <- sqlQuery(dbhandle, x)

     # Loop thru dataframe dflist and run percentile and write to file
     lapply(dflist, function(df) {

     write.table(matrix(quantile(dflist$los, c(0.10, 0.25, 0.50, 0.75, 0.90))[c(1,2,3,4,5)], nrow=1),file="/foo.txt", col.names=FALSE, row.names=FALSE, append = TRUE)
     NULL
     })



}

1 个答案:

答案 0 :(得分:2)

是的,有办法。简单的方法是创建一个新的lapply函数来直接存储它,但我会告诉你一种方法在你当前的lapply函数中做到这一点(以避免循环两次):

数据

a <- runif(50)
b <- runif(50)
df <- data.frame(a,b)

<强>解决方案

#initiate a list
mylist <- list()

lapply(df, function(x) {
  #save quantile in the list on each loop
  #notice the <<- operator below that will modify the list in the global environment
  mylist[[length(mylist)+1]] <<- quantile(x, c(0.10, 0.25, 0.50, 0.75, 0.90))

  #also do your write.table function below as you did
  write.table(matrix(quantile(dflist$los, c(0.10, 0.25, 0.50, 0.75, 0.90))[c(1,2,3,4,5)], nrow=1),file="/foo.txt", col.names=FALSE, row.names=FALSE, append = TRUE)
})

它将起到以下作用:

df2 <- data.frame(mylist)
colnames(df2) <- c('a','b')

> df2
            a         b
10% 0.1143816 0.0386159
25% 0.2301640 0.2265687
50% 0.4753750 0.4696076
75% 0.7633871 0.6843929
90% 0.9312094 0.8813031

这样它只适用于一个lapply,你也可以在数据框中保存分位数。