【发布时间】:2019-06-03 23:26:36
【问题描述】:
我正在使用一个自制的中缀函数,它只是计算 列中观察值之间的百分比增长。
options(digits=3)
`%grow%` <- function(x,y) {
(y-x) / x * 100
}
test <- data.frame(a=c(101,202,301), b=c(123,214,199), h=c(134, 217, 205))
然后我在我的玩具数据库中使用lapply 以添加两个新列。
test[,4:5] <- lapply(1:(ncol(test)-1), function(i) test[,i] %grow% test[,(i+1)])
test
#Output
a b h V4 V5
1 101 123 134 21.78 8.94
2 202 214 217 5.94 1.40
3 301 199 205 -33.89 3.02
考虑到我只有三列而且我可以写test[,4:5],这很容易。现在笼统地说:如果我们有 n 列使用列索引,如何做到这一点?
我的意思是我想从最后一个开始为给定数据库创建 n-1 列。比如:
test[,(last_current_column+1):(last_column_created_using_function)]
考虑到我在其他帖子中读到的内容,使用我的示例,test[,(last_current_column+1): 可以写成:
test[,(ncol(test)+1):]
但第二部分仍然缺失,我不知道如何写。
我希望我说清楚了。我非常感谢任何评论或建议。
2019 年快乐 :)
【问题讨论】:
标签: r database dataframe functional-programming