yoyong
April 22, 2021, 11:59am
1
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
Leon
April 22, 2021, 12:02pm
2
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!
yoyong
April 22, 2021, 12:18pm
3
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.
srpike
April 22, 2021, 12:21pm
4
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}")
)
5 Likes
system
Closed
April 29, 2021, 12:22pm
5
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.