将列中的所有值与不同数据帧中的行中的相应值相乘

时间:2021-11-06 07:38:50

I am new to R. I have two data frames as

我是R.的新手。我有两个数据框

PriceData

PriceData

Date        AAPL    MSFT    GOOG
12/3/2014   100     45      522
12/2/2014   99      45      517
12/1/2014   97      45      511
11/28/2014  97      44      508

QuantityData

QuantityData

Symbol  Position
MSFT    1000
AAPL    1200
GOOG    1300

Now I want to calculate market value. So output should be like this

现在我想计算市场价值。所以输出应该是这样的

Date        AAPL    MSFT    GOOG
12/3/2014   120000  45000   678600
12/2/2014   118800  45000   672100
12/1/2014   116400  45000   664300
11/28/2014  116400  44000   660400

1 个解决方案

#1


1  

You can try

你可以试试

indx <- match(colnames(PriceData)[-1], QuantityData$Symbol)
PriceData[,-1][,indx] <- PriceData[,-1][,indx]*
                        QuantityData[,2][col(PriceData[,-1])]

PriceData
#       Date   AAPL  MSFT   GOOG
#1  12/3/2014 120000 45000 678600
#2  12/2/2014 118800 45000 672100
#3  12/1/2014 116400 45000 664300
#4 11/28/2014 116400 44000 660400

Or

要么

PriceData[,-1][,indx] <- t(t(PriceData[,-1][,indx])*QuantityData[,2])

#1


1  

You can try

你可以试试

indx <- match(colnames(PriceData)[-1], QuantityData$Symbol)
PriceData[,-1][,indx] <- PriceData[,-1][,indx]*
                        QuantityData[,2][col(PriceData[,-1])]

PriceData
#       Date   AAPL  MSFT   GOOG
#1  12/3/2014 120000 45000 678600
#2  12/2/2014 118800 45000 672100
#3  12/1/2014 116400 45000 664300
#4 11/28/2014 116400 44000 660400

Or

要么

PriceData[,-1][,indx] <- t(t(PriceData[,-1][,indx])*QuantityData[,2])