我有一个带有 3 列的 data.frame:日期、费率、价格。我想添加来自矩阵的列,在费率之后和价格之前。
df = tibble('date' = c('01/01/2000', '02/01/2000', '03/01/2000'),
'rate' = c(7.50, 6.50, 5.54),
'price' = c(92, 94, 96))
我使用输出矩阵的函数计算了速率的滞后:
rate_Lags = matrix(data = c(NA, 7.50, 5.54, NA, NA, 7.50), ncol=2, dimnames=list(c(), c('rate_tMinus1', 'rate_tMinus2'))
我想使用名称索引而不是列顺序在费率之后(和价格之前)插入那些滞后。
add_column
tibble 包( Adding a column between two columns in a data.frame )中的函数不起作用,因为它只接受一个原子向量(因此,如果我有 10 个滞后,我将不得不调用 add_column 10 次)。我可以用 apply
在我的 rate_Lags
矩阵。但是,然后我丢失了 rate_Lags
中的暗名。矩阵。如果我知道特定列名的位置(任何检索列名位置的函数?),使用数字索引(子集)( https://stat.ethz.ch/pipermail/r-help/2011-August/285534.html )可以工作。
有没有什么简单的方法可以插入一堆列 s 在数据框/tibble 对象中的特定位置?
最佳答案
您可能会忽略以下内容
library(dplyr)
I <- which(names(df) == "rate")
if (I == ncol(df)) {
cbind(df, rate_Lags)
} else {
cbind(select(df, 1:I), rate_Lags, select(df, (I+1):ncol(df)))
}
# date rate rate_tMinus1 rate_tMinus2 price
# 1 0.0005 7.50 NA NA 92
# 2 0.0010 6.50 7.50 NA 94
# 3 0.0015 5.54 5.54 7.5 96
关于r - 在数据框中的特定位置添加列的优雅方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50920153/