通过for循环将字符串参数传递给函数

时间:2012-03-28 16:49:04

标签: r arguments trim zoo

我遇到了将字符串类型参数传递给函数的问题。例如:

    date.range <- seq.Date(from=as.Date('2011-01-01'), 
                           to=as.Date('2011-12-31'), by='1 day')
    a.zoo<-zoo(1:365,date.range); 
    b.zoo<-zoo(2:366, date.range); 
    c.zoo<-zoo(3:367, date.range)
    zooNames<-c("a.zoo", "b.zoo", "c.zoo")
    for(name in zooNames){
        aggind.day<-format(index(name), '%Y-%m-%d')
        name.stitch<-str_c(name,'.avg')
        name.stitch<-aggregate(coredata(name), aggind.day, mean)
    }
    rm(a.zoo, b.zoo, c.zoo, zooNames, name, name.stitch, aggind.day)

返回错误:无效的'trim'参数。

1 个答案:

答案 0 :(得分:0)

引发错误的原因是您尝试应用format参数分配给trim类型值(即character)的%Y-%m-%d函数。但是trim的类型应为boolean,即代码:

format(1, '%Y-%m-%d')

抛出:

  

prettyNum(.Internal(format(x,trim,digits,nsmall,width,   3L ,:无效的“修剪”参数

您可以使用getassign函数来获取和设置变量。请参见下面的代码。下面的算法计算一年中工作日的平均数据。对于工作日标识lubridate程序包wday,使用了功能。

library(zoo)
library(lubridate)
date.range <- seq.Date(from=as.Date('2011-01-01'), 
                       to=as.Date('2011-12-31'), by='1 day')
a.zoo <- zoo(1:365,date.range); 
b.zoo <- zoo(2:366, date.range); 
c.zoo <- zoo(3:367, date.range)
zooNames <- c("a.zoo", "b.zoo", "c.zoo")

for(name in zooNames){
  z <- get(name)
  w_days <- wday(date.range, label = TRUE, locale = "English_United States")
  agg  <- aggregate(z, w_days, mean)
  assign(paste0(name, ".avg"), agg)
}

a.zoo.avg
b.zoo.avg
c.zoo.avg

输出:

> a.zoo.avg
  Sun   Mon   Tue   Wed   Thu   Fri   Sat 
180.5 181.5 182.5 183.5 184.5 185.5 183.0 
> a.zoo.avg
  Sun   Mon   Tue   Wed   Thu   Fri   Sat 
180.5 181.5 182.5 183.5 184.5 185.5 183.0 
> b.zoo.avg
  Sun   Mon   Tue   Wed   Thu   Fri   Sat 
181.5 182.5 183.5 184.5 185.5 186.5 184.0 
> c.zoo.avg
  Sun   Mon   Tue   Wed   Thu   Fri   Sat 
182.5 183.5 184.5 185.5 186.5 187.5 185.0