user13759541
user13759541

Reputation: 35

How can I perform multiplication in r using a loop that references column names?

Ok, so I have a DF with 7,000 columns and 1,000 rows. All data is numeric. Each column has a unique name.

I also have a second data frame with 100 rows. Each row has a name and a value. The names may or may not match the names of the first DF. Example below:

a <- c(1,2,3)
b <- c(4,5,6)
c <- c(7,8,9)
df1 <- data.frame(a,b,c)

v1 <- c('a','c','f','g','z')
v2 <- c(1,3,5,2,0)
df2 <- data.frame(v1,v2)

What I need to do is take each value for v1 and search for a match in the column names of DF1. If there is a match in names, then I need to multiply the value of v2 by every row in that column for that match.

The values in v1 may or may not have a match in DF1. I tried to get there with lapply but it wasn't quite working. Any advice is helpful. Thank you.

Upvotes: 0

Views: 321

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388862

Try :

#Get the value to multiply in each column
mult <- df2$v2[match(names(df1), df2$v1)]
#[1]  1 NA  3

#Replace the value which is absent in df2 with 1 
#so we keep the value same
mult[is.na(mult)] <- 1
#[1] 1 1 3

#multiply
res <- sweep(df1, 2, mult, `*`)
res
#  a b  c
#1 1 4 21
#2 2 5 24
#3 3 6 27

Upvotes: 1

Related Questions