Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to multiply entire row with a matching row name in another dataframe?

Tags:

r

Let's suppose I have the following dataframes:

    test <- data.frame(X = c(1,2,3), Y = c(4,5,6), row.names = c("T1", "T2", "T3"))

    test2 <- data.frame(mean = c(1,2,5), row.names = c("T1", "T2", "T3"))

I want to multiply all rows in the test dataframe by the value in the test2 dataframe, matched by row name. How do I do this to get an answer like this:

    answer <- data.frame(X = c(1,4,15), Y = c(4,10,30), row.names = c("T1", "T2", "T3"))
like image 387
Marcus Avatar asked Jun 18 '20 10:06

Marcus


1 Answers

You can do

test * test2[rownames(test), "mean"]
#     X  Y
# T1  1  4
# T2  4 10
# T3 15 30
like image 161
markus Avatar answered Nov 15 '22 01:11

markus