简体   繁体   中英

Multiply columns with rows by matching column name and row name in 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

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

If you use Names for rownames instead in ref , you could do something like this as well

rownames(ref) <- ref$Names #assign rownames
ref$Names <- NULL #drop col

i <- intersect(rownames(ref), colnames(data)) #find intersect
mapply(`*`, ref[i, ], data[, i]) #perform multiplication
#     [,1] [,2]
#[1,]    5   20
#[2,]   10   10

this should work:

for (n in seq(along = names(data))) {
    data[,n] <- data[,n] * ref$Values[which(ref$Names == names(data)[n])]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM