Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

environment issue

Tags:

for-loop

r

sapply

e <<- data.env ## here i am storing my rdata
data_frames <- Filter(function(x) is.data.frame(get(x)), ls(envir = e)) ## getting only dataframe
for(i in data_frames) e[[i]] <<- mytest_function(e[[i]]) ###  here i am iterating the dataframe 

Now, how do I convert the for loop into an apply function? The loop takes so long to iterate.

like image 511
Fariya Avatar asked Jun 30 '26 22:06

Fariya


2 Answers

Ok here some basic demonstration and I think it is a good call to use apply especially because of the environment issues in loops and such.

# lets create some data.frames
df1 <- data.frame(x = LETTERS[1:3], y = rep(1:3))
df2 <- data.frame(x = LETTERS[4:6], y = rep(4:6))

# what df's are we going to "loop" over
data_frames <- c("df1", "df2")

# just some simple function to paste x and y from your df's to a new column z
mytest_function <- function(x) {
  df <- get(x)
  df$z <- paste(df$x, df$y)
  df
}

# apply over your df's and call your function for every df
e <- lapply(data_frames, mytest_function)

# note that e will be a list with data.frames
e

[[1]]
  x y   z
1 A 1 A 1
2 B 2 B 2
3 C 3 C 3

[[2]]
  x y   z
1 D 4 D 4
2 E 5 E 5
3 F 6 F 6

# most of the time you want them combined
e <- do.call(rbind, e)

e
  x y   z
1 A 1 A 1
2 B 2 B 2
3 C 3 C 3
4 D 4 D 4
5 E 5 E 5
6 F 6 F 6
like image 190
Merijn van Tilborg Avatar answered Jul 02 '26 13:07

Merijn van Tilborg


It's unclear what you want the result to be. However, if you are just wanting to apply a function to each column in a dataframe, then you can just use sapply.

sapply(df, function(x) mytest_function(x))

Or you can use the purrr package.

purrr::map(df, function(x) mytest_function(x)) %>% 
   as.data.frame

If you have a list of a dataframes and are applying a function to each dataframe, then you can also use purrr.

library(purrr)

purrr::map(data_frames, mytest_function)
like image 43
AndrewGB Avatar answered Jul 02 '26 13:07

AndrewGB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!