Home > Mobile >  How to convert loop into apply function
How to convert loop into apply function

Time:12-15

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.

CodePudding user response:

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

CodePudding user response:

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 if you already have a list of a dataframes and are applying a function to each dataframe, then I would use purrr.

library(purrr)

purrr::map(data_frames, mytest_function)

CodePudding user response:

When you want to convert a loop into an apply function I usually go for lapply but it depends on the situation :

my_f <- function(x) {
mytest_function(e[[x]])
}
my_var <- lapply(1:length(data_frames), my_f)
  • Related