[英]basic matrix/data.frame arithmetic in R
I am finding it puzzling that I am not able to do simple matrix arithmetic in R. Is this really not possible? 我无法在R中执行简单的矩阵算术,这令人感到困惑。这真的不可能吗? I want to take the values in 1 dataframe and subtrack them row all of the columns in another dataframe. 我想采用1个数据框中的值,并将其子跟踪到另一个数据框中的所有列。 Seems like this should be easy but I am not finding anything, although there is a "psych" package which as a function but doesn't give the expected results. 看起来像这样应该很容易,但是我什么也没找到,尽管有一个“心理”程序包可以作为功能,但不能给出预期的结果。 Also seems like it should not be necessary. 似乎也没有必要。 Any tips. 有小费吗。 Much appreciated. 非常感激。
> NROW(arData1[c(gsub(" ", ".",portfolio1), "benchmark")])
[1] 51
> NCOL(arData1[c(gsub(" ", ".",portfolio1), "benchmark")])
[1] 4
> NROW(arData1[gsub(" ", ".", treasuries)])
[1] 51
> NCOL(arData1[gsub(" ", ".", treasuries)])
[1] 1
ExRet1 <- arData1[c(gsub(" ", ".",portfolio1), "benchmark")] - arData1[gsub(" ", ".", treasuries)]
Error in Ops.data.frame(arData1[c(gsub(" ", ".", portfolio1), "benchmark")], :
- only defined for equally-sized data frames
The problem has to do with the way you are indexing. 问题与您建立索引的方式有关。
df["colname"]
extracts the column colname
as a data frame . 提取列colname
作为数据框 。 If you subtract two data frames, R does this column-wise and row-wise, so both data frames must have the same number of columns. 如果减去两个数据帧,R会按列和按行进行此操作,因此两个数据帧的列数必须相同。
However, you can extract colname
as a vector using [[
, as in 但是,您可以使用[[
提取colname
作为矢量 ,如
df[["colname"]]
If you subtract a vector from a data frame, that vector is subtracted from each column in df
. 如果从数据帧中减去一个向量,则会从df
每一列中减去该向量。
df <- data.frame(x=1:5,y=11:15,z=21:25,A=31:35)
df[c("x","y","z")] - df["A"]
# Error in Ops.data.frame(df[c("x", "y", "z")], df["A"]) :
# - only defined for equally-sized data frames
df[c("x","y","z")] - df[["A"]]
# x y z
# 1 -30 -20 -10
# 2 -30 -20 -10
# 3 -30 -20 -10
# 4 -30 -20 -10
# 5 -30 -20 -10
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.