Home > Blockchain >  loop multiplication on different datasets with same variable names
loop multiplication on different datasets with same variable names

Time:12-19

Hey I'm sure I'm missing something simple with mapping, but I can't get it to work. I want to use a loop to do the same calculation for multiple dataframes that have the same name. Basically, I want this loop to not throw an error:

mtcars1 <- mtcars
mtcars2 <- mtcars

for(x in c(mtcars1, mtcars2)){
  x$new <- x$mpg * x$cyl
}

So that at the end, both mtcars1 and mtcars2 have a new variable called new, that is mpg * cyl.

CodePudding user response:

The for loop does not work as you think, and more important, the effect of c(mtcars1, mtcars2) is not what you think, to see so do

test <- c(mtcars1, mtcars2)
length(test)
str(test)

You need to replace the c with list. Below is one solution:

mtcars1 <- mtcars
mtcars2 <- mtcars
test <- list(mtcars1, mtcars2) 

newtest <- lapply(test, FUN=function(x) 
                  within(x, new <- mpg * cyl))

CodePudding user response:

If you first put your dataframes into a list, you can index into each using seq_along():

dfs <- list(mtcars1 = mtcars, mtcars2 = mtcars)

for (i in seq_along(dfs)) {
  dfs[[i]]$new <- dfs[[i]]$mpg * dfs[[i]]$cyl
}

Or, using lapply():

dfs <- lapply(dfs, \(x) {
  x$new <- x$mpg * x$cyl
  x
})

Result from either approach:

#> head(dfs$mtcars1)
                   mpg cyl disp  hp drat    wt  qsec vs am gear carb   new
Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4 126.0
Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4 126.0
Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1  91.2
Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1 128.4
Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2 149.6
Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1 108.6

If you really want to leave your dataframes loose in the environment, you could do something like

for (nm in c("mtcars1", "mtcars2")) {
  x <- get(nm)
  x$new <- x$mpg * x$cyl
  assign(nm, x)
}

Result:

#> head(mtcars1)
                   mpg cyl disp  hp drat    wt  qsec vs am gear carb   new
Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4 126.0
Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4 126.0
Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1  91.2
Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1 128.4
Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2 149.6
Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1 108.6
  •  Tags:  
  • r
  • Related