[英]Subtract a row of prices in one dataframe from columns in another
I have a dataframe with 163 columns with unique names, say (x1, x2, x3, x4 ....) each of these columns has a series of returns (0.248, -0.00384, etc). 我有一个数据框,其中包含163个具有唯一名称的列,例如(x1,x2,x3,x4 ....)。这些列中的每个列都有一系列返回值(0.248,-0.00384等)。
**DF1**
x1 x2 x3 x4 .....
0.248 -0.00384 0.0394 0.0053 .....
In another dataframe I have one column with a list of the same unique names (x1, x2, x3, x4 ...) and another with a list of numbers (0.005, .001, etc). 在另一个数据帧中,我有一列带有相同唯一名称(x1,x2,x3,x4 ...)的列表,另一列带有数字列表(0.005,.001等)。
**DF2**
x1 0.005
x2 0.001
x3 0.005
x4 0.0005
...
My ultimate goal is to return a dataframe with the 163 columns (x1, x2, etc) with each columns net returns (so the x1 column is the original returns subtracted by 0.005, x2 column is the original returns subtracted by 0.001, etc). 我的最终目标是返回一个包含163列(x1,x2等)的数据帧,每列的净收益(因此x1列是原始收益减去0.005,x2列是原始收益减去0.001,依此类推)。
So far I tried sorting the second dataframe, transposing and using unlist to get a vector of numbers, which I could then subtract from each column (but I cant figure out how to subtract from each column). 到目前为止,我尝试对第二个数据帧进行排序,转置并使用unlist来获取数字向量,然后可以从每一列中减去(但是我无法弄清楚如何从每一列中减去)。 Any help with figuring out how to do this would be really helpful.
弄清楚如何做到这一点的任何帮助将非常有帮助。 The list of unique names in the second dataframe are the same as the first dataframe, which is also sorted alphabetically, so it doesnt need to be matched up (both sorted will line up).
第二个数据帧中的唯一名称列表与第一个数据帧相同,后者也按字母顺序排序,因此不需要匹配(两个排序都会对齐)。
In case, the colnames of DF1
and rownames of DF2
are not in the same order, you can use match
如果
DF1
和DF2
名称的顺序不同,则可以使用match
DF1-DF2[match(colnames(DF1), rownames(DF2)),1][col(DF1)]
Should work if either or both datasets are not in the same order. 如果其中一个或两个数据集的顺序不同,则应该起作用。 For example
例如
set.seed(65)
DF1N <- DF1[,sample(colnames(DF1))]
DF1N-DF2[match(colnames(DF1N), rownames(DF2)),1][col(DF1N)]
If they are in order 如果他们有秩序
DF1-DF2[,1][col(DF1)]
set.seed(24)
DF1 <- as.data.frame(matrix(rnorm(40*10), ncol=10,
dimnames=list(NULL, paste0("x", 1:10))) )
set.seed(42)
DF2 <- data.frame(Col1=rnorm(10, 0.01))
row.names(DF2) <- sample(paste0("x",1:10))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.