Marco Pastor Mayo
Marco Pastor Mayo

Reputation: 853

Create variables in data frame with for loop

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
}

Upvotes: 1

Views: 1513

Answers (2)

akrun
akrun

Reputation: 887891

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)))

Upvotes: 0

arg0naut91
arg0naut91

Reputation: 14774

Something along the lines of:

for (i in 1:2) {

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

}

Upvotes: 2

Related Questions