I have a main data frame (mydata) and two secondary ones (df1, df2) such as follows:
x <- c(1, 2, 3, 4, 5)
y <- c(5, 4, 3, 2, 1)
mydata <- data.frame(x)
df1 <- data.frame(y)
df2 <- data.frame(y)
df2$y <- y+1 #This way, the columns in the df have the same name but different values.
I want to create new columns in mydata based on a formula with the variables in df1 and df2 like this:
mydata$new1 <- mydata$x*df1$y
mydata$new2 <- mydata$x*df2$y
Is there a way I can do this with a for loop? This is what I had in mind:
for (i in 2) {
mydata$paste0("new", i) <- mydata$x*dfpaste0(i)$y
}