我正在尝试在绘制数据集之前构建它。我决定使用函数工厂gammaplot.ff()
,我的代码的第一个版本如下所示:
PowerUtility1d <- function(x, delta = 4) {
return(((x+1)^(1 - delta)) / (1 - delta))
}
PowerUtility1d <- Vectorize(PowerUtility1d, "x")
# function factory allows multiparametrization of PowerUtility1d()
gammaplot.ff <- function(type, gamma) {
ff <- switch(type,
original = function(x) PowerUtility1d(x/10, gamma),
pnorm_wrong = function(x) PowerUtility1d(2*pnorm(x)-1, gamma),
pnorm_right = function(x) PowerUtility1d(2*pnorm(x/3)-1, gamma)
)
ff
}
gammaplot.df <- data.frame(type=numeric(), gamma=numeric(),
x=numeric(), y=numeric())
gammaplot.gamma <- c(1.1, 1.3, 1.5, 2:7)
gammaplot.pts <- (-1e4:1e4)/1e3
# building the data set
for (gm in gammaplot.gamma) {
for (tp in c("original", "pnorm_wrong", "pnorm_right")) {
fpts <- gammaplot.ff(tp, gm)(gammaplot.pts)
dataChunk <- cbind(tp, gm, gammaplot.pts, fpts)
colnames(dataChunk) <- names(gammaplot.df)
gammaplot.df <- rbind(gammaplot.df, dataChunk)
}
}
# rbind()/cbind() cast all data to character, but x and y are numeric
gammaplot.df$x <- as.numeric(as.character(gammaplot.df$x))
gammaplot.df$y <- as.numeric(as.character(gammaplot.df$y))
事实证明,整个数据框都包含字符数据,所以我必须手动将其转换回来(首先我花了一段时间才发现!)。SO 搜索表明发生这种情况是因为类型变量是字符。为了避免这种情况(您可以想象构建数据集时字符数据的性能问题!)我稍微更改了代码:
gammaplot.ff <- function(type, gamma) {
ff <- switch(type,
function(x) PowerUtility1d(x/10, gamma),
function(x) PowerUtility1d(2*pnorm(x)-1, gamma),
function(x) PowerUtility1d(2*pnorm(x/3)-1, gamma)
)
ff
}
for (gm in gammaplot.gamma) {
for (tp in 1:3) {
fpts <- gammaplot.ff(tp, gm)(gammaplot.pts)
dataChunk <- cbind(tp, gm, gammaplot.pts, fpts)
colnames(dataChunk) <- names(gammaplot.df)
gammaplot.df <- rbind(gammaplot.df, dataChunk)
}
}
这对我来说很好,但我丢失了一个不言自明的字符参数,这是一个缺点。有没有办法在不将所有数据隐式转换为字符的情况下保留函数工厂的第一个版本?
如果有其他方法可以达到相同的结果,我很乐意尝试一下。