multiply a column with other columns in a data frame

Hi everyone.

I would like to multiply F1 column with F2, F3, F4. This should result to 4 additional columns in my dataset.
Not sure how to go about it.

df1<-data.frame(F1=c(1,2,3,4),F2=c(1,5,8,9),F3=c(2,3,4,6)),F4=c(3,4,5,8))

Appreciate the help.

Thanks!

yoyong

1 Like

Would this work for you?

# Load libraries
library("tidyverse")

# Define data
df1 <- data.frame(
  F1 = c(1, 2, 3, 4),
  F2 = c(1, 5, 8, 9),
  F3 = c(2, 3, 4, 6),
  F4 = c(3, 4, 5, 8))

# Augment
df1 %>% 
  mutate(
    F1_F1 = F1 * F1,
    F1_F2 = F1 * F2,
    F1_F3 = F1 * F3,
    F1_F4 = F1 * F4
)

Hope it helps! :slightly_smiling_face:

Thanks Leon.

I have tried this. I was just wondering if there is another way of doing it especially having a large dataset. I need to multiply one column with almost a hundred columns. :slight_smile:

In case you have lots of columns, you can also do it this way. Look up tidy select for options for selecting columns (instead of everything():

# Load libraries
library("tidyverse")

# Define data
df1 <- data.frame(
  F1 = c(1, 2, 3, 4),
  F2 = c(1, 5, 8, 9),
  F3 = c(2, 3, 4, 6),
  F4 = c(3, 4, 5, 8))

# Alternative using dplyr::across
df1 %>% 
  mutate(
    across(everything(), ~ .x* F1, .names = "F1_{.col}")
  )
4 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.