我正在学习如何使用sparkTable包。我正在创建具有sparkLine的表,后面跟着一定数量的列(不是固定的)。列都实现了相同的功能:显示时间序列的n‘to元素,四舍五入到2位数。例如,星星图后面的第1列将显示第1时间点、第2列、第2数据点的值,等等。就目前而言,我通过以下方式处理这一问题:
首先,声明一个函数列表,允许在数据中显示尽可能多的时间点。
get.values <- list(function(x) round(x[1],2),
function(x) round(x[2],2),
function(x) round(x[3],2),
function(x) round(x[4],2),
function(x) round(x[5],2),
function(x) round(x[6],2),
function(x) round(x[7],2),
function(x) round(x[8],2),
function(x) round(x[9],2),
function(x) round(x[10],2))然后,在调用newSparkTable时,我将tableContent参数“展开”为数据中显示的时间点的数量:
st <- newSparkTable(my.data, tableContent = c(list(newSparkLine()),
get.values[1:max(my.data$time)]),
...)这很好,但是我认为必须有一种更灵活的方法(我在考虑Python中的lambda函数,或者类似的东西)。最受欢迎的想法。
编辑
我越来越接近它了。对此代码进行评估的一种方法可以做到这一点:
paste("function(x) round(x[", 1:max(my.data$time), "],2)", sep="")
# For instance if max(my.data$time)==10
> paste("function(x) round(x[", 1:10, "],2)", sep="")
[1] "function(x) round(x[1],2)" "function(x) round(x[2],2)" "function(x) round(x[3],2)"
[4] "function(x) round(x[4],2)" "function(x) round(x[5],2)" "function(x) round(x[6],2)"
[7] "function(x) round(x[7],2)" "function(x) round(x[8],2)" "function(x) round(x[9],2)"
[10] "function(x) round(x[10],2)"但随后:
> eval(parse(text=paste("function(x) round(x[", 1:10, "],2)", sep="")))
function(x) round(x[10],2)只有最后一个得到了评估。
发布于 2014-11-09 09:23:57
使用lapply与工厂函数一起创建函数列表:
round.factory = function(index) {
j = index
function(x) round(x[j], 2)
}
get.values = lapply(1:10, round.factory)中间变量j对于将index的值绑定到本地范围是必要的。
https://stackoverflow.com/questions/26825126
复制相似问题