将两个 xts 对象相互相乘

Multiplying two xts objects with each other

我有一个 xts 列表,看起来像这样(我的列表称为价格):

head(prices[[1]])

           X        ID      Name            Price              Shares.Outstanding
1980-03-31 "170481" "55160" "Donec Non Ltd" "5,72762874283858" "973,74375"       
1980-04-30 "170482" "55160" "Donec Non Ltd" "7,60702431506945" "973,74375"       
1980-05-30 "170483" "55160" "Donec Non Ltd" "6,97838217177628" "973,74375"       
1980-06-30 "170484" "55160" "Donec Non Ltd" "8,24558297069908" "973,74375"       
1980-07-31 "170485" "55160" "Donec Non Ltd" "7,92929698195742" "973,74375" 

我想将价格乘以特定日期的已发行股票。我试着这样做:

day <- prices[[1]]["1980-06-30"]
market_value <- coredata(day[,4]) * coredata(day[,5])

但是,它给了我错误:二元运算符的非数字参数。 我也尝试使用 as.numeric 而不是 coredata 但这也不起作用。

谢谢!

您正在尝试乘以字符,这就是 R 抛出错误的原因。

首先,您应该将这些变量更改为数字,并且必须将逗号替换为点:

library(dplyr)

prices[[1]] <- prices[[1]] %>% mutate(Price = as.numeric(sub(",", ".", Price, fixed = TRUE)), 
                                      Shares.Outstanding = as.numeric(sub(",", ".", Shares.Outstanding, fixed = TRUE)))
    

然后你可以将它们相乘!