Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiply columns with rows by matching column name and row name in R

Tags:

r

I have a data frame which looks like this

> data
  A B
1 1 2
2 2 1

I have a reference data frame which looks like this

> ref
  Names Values
1     A      5
2     B     10

I want to multiply each column by corresponding row in Ref having same Name

the result should be this

> result
   A  B
1  5 20
2 10 10

What is the fastest way to achieve this in R? Any help would be greatly appreciated

like image 927
Rajarshi Bhadra Avatar asked Oct 19 '22 15:10

Rajarshi Bhadra


1 Answers

We can match the column names of 'data' with 'Names' column of 'ref', get the corresponding 'Values' based on the numeric index and then multiply by replicating the ref$Values

data*ref$Values[match(names(data), ref$Names)][col(data)]
#   A  B
#1  5 20
#2 10 10
like image 120
akrun Avatar answered Oct 21 '22 04:10

akrun