简体   繁体   中英

R - Multiply select columns in a dataframe by matching columns in a second dataframe

In R I'm trying to multiply select columns in a dataframe (df1) with matching columns in a second dataframe (df2). The number of rows is unequal (just 1 for df2) and there are columns that I wish to retain but do not wish to multiply. An example follows:

df1 <- data.frame(group = c('A','B','C','A'), var1 = c(1,0,1,0), var2 = c(0,1,1,0))

df2 <- data.frame(var1 = 0.06, var2 = 0.04)

The expected result would be:

Group   var1   var2
A       0.06   0
B       0      0.04
C       0.06   0.04
A       0      0

I'm happy to adjust the format of df2 if required. A tidyverse solution would be great.

I've read several other questions attempting to do something similar but I can't get them to work in my situation eg

data.frame(Map(function(x,y) if(all(is.numeric(x),is.numeric(y))) x * y
                          else x, df1, df2))
# Multiply's by position not name

Thanks in advance.

We can make the lengths same with rep or col and then do the multiplication

nm1 <- intersect(names(df1), names(df2))
df1[nm1] <-  df1[nm1] * unlist(df2[nm1])[col(df1[nm1])]
df1
#  group var1 var2
#1     A 0.06 0.00
#2     B 0.00 0.04
#3     C 0.06 0.04
#4     A 0.00 0.00

Or using Map

df1[nm1] <- Map(`*`, df1[nm1], df2[nm1])

Or using tidyverse

library(dplyr)
library(purrr)
map2_dfc(select(df1, nm1), select(df2, nm1),  `*`) %>%
     bind_cols(select(df1, -one_of(nm1)), .)
#  group var1 var2
#1     A 0.06 0.00
#2     B 0.00 0.04
#3     C 0.06 0.04
#4     A 0.00 0.00

We can use sweep in base R after getting the common column names from both the dataframe.

cols <- intersect(colnames(df1), colnames(df2))
df1[cols] <- sweep(df1[cols], 2, unlist(df2[cols]), `*`)

df1
#  group var1 var2
#1     A 0.06 0.00
#2     B 0.00 0.04
#3     C 0.06 0.04
#4     A 0.00 0.00

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