我遇到了将字符串类型参数传递给函数的问题。例如:
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'参数。
答案 0 :(得分:0)
引发错误的原因是您尝试应用format
参数分配给trim
类型值(即character
)的%Y-%m-%d
函数。但是trim
的类型应为boolean
,即代码:
format(1, '%Y-%m-%d')
抛出:
prettyNum(.Internal(format(x,trim,digits,nsmall,width, 3L ,:无效的“修剪”参数
您可以使用get
和assign
函数来获取和设置变量。请参见下面的代码。下面的算法计算一年中工作日的平均数据。对于工作日标识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