NicolasBourbaki
NicolasBourbaki

Reputation: 987

R: Change objects inside loop

a <- data.frame(x = c(1, 2))
b <- data.frame(x = c(3, 4))

for (df in list(a, b)) {
  print(df)
  df$y <- c(5, 6)
}

Each of the data frames gets printed out correctly, but adding an additional column fails.
Extensive web search suggested something like

lapply(list(a, b), function(df){
  df$y <- c(5, 6)
})

but this didn't help me.

What I'd be also very interested is, why the print statement in the for loop works, but the addition of the y column fails.

This is surprising for me.

Upvotes: 2

Views: 775

Answers (2)

> a <- data.frame(x = c(1, 2))
> b <- data.frame(x = c(3, 4))
> l <- list(a = a, b = b)
> list2env(lapply(l, function(x) {x$y <- c(5, 6);x}), envir = .GlobalEnv)
<environment: R_GlobalEnv>
> a
  x y
1 1 5
2 2 6
> b
  x y
1 3 5
2 4 6

Upvotes: 0

symbolrush
symbolrush

Reputation: 7457

You have to return the df's with that additional column. Try:

lapply(list(a, b), function(df){
  df$y <- c(5, 6); return(df)
})

The output is:

[[1]]
  x y
1 1 5
2 2 6

[[2]]
  x y
1 3 5
2 4 6

As @dash2 supposes you may want to assign those changed df's to your list of df's. So the full code could look like:

a <- data.frame(x = c(1, 2))
b <- data.frame(x = c(3, 4))

l <- list(a, b)
l <- lapply(l, function(df){ df$y <- c(5, 6); return(df) })

Upvotes: 1

Related Questions