r - 如何根据 R 中的索引向数据框添加列? (参见示例)

标签 r database dataframe functional-programming

我正在使用一个自制的中缀函数,它简单地计算 列中观察值之间的百分比增长。

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 年快乐:)

最佳答案

另一种方法是:

#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),
                   d=c(156,234,235))
#     a   b   h   d
# 1 101 123 134 156
# 2 202 214 217 234
# 3 301 199 205 235


seqcols <- seq_along(test) # saved just to improve readability
test[,seqcols[-length(seqcols)] + max(seqcols)] <- lapply(seqcols[-length(seqcols)], 
                     function(i) test[,i] %grow% test[,(i+1)])
test
#     a   b   h   d     V5   V6    V7
# 1 101 123 134 156  21.78 8.94 16.42
# 2 202 214 217 234   5.94 1.40  7.83
# 3 301 199 205 235 -33.89 3.02 14.63

与@Ronak Shah的第二个解决方案类似,只是使用purrr中的map2_df:

cbind(test,
      new=purrr::map2_df(test[seqcols[-length(seqcols)]], test[seqcols[-1]], `%grow%`),
      deparse.level=1)
#     a   b   h   d  new.a new.b new.h
# 1 101 123 134 156  21.78  8.94 16.42
# 2 202 214 217 234   5.94  1.40  7.83
# 3 301 199 205 235 -33.89  3.02 14.63

关于r - 如何根据 R 中的索引向数据框添加列? (参见示例),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54105880/

相关文章:

r - 将数据框与 SpatialPolygonsDataFrame 合并

r - R语言中的特殊字符

database - db4o:压缩/收缩

python - 根据列在DataFrame中插入值

R 如何在满足条件时开始按组计数

r - 加快RData加载

mysql - 更新 MySQL 中 2 个表之间的电子邮件匹配 - 黑名单

sql-server - 如何在链接服务器(SQL Server 2012)上查找具有特定表的数据库?

python - 如何在 Pandas 中正确旋转或 reshape 时间序列数据框?

R:tidyr::spread 的编程替代方案?