1

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
}

2 Answers 2

2

Something along the lines of:

for (i in 1:2) {

  mydata[[as.symbol(paste0('new', i))]] <- mydata$x*get(paste0("df", i))$y

}
Sign up to request clarification or add additional context in comments.

Comments

0

We could also use mget to get all the object values in a list and multiply with the concerned vector

mydata[paste0("new", 1:2)] <- mydata$x * data.frame(mget(paste0("df", 1:2)))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.