wzbillings
wzbillings

Reputation: 378

Can I rewrite this loop in R using `lapply`?

I have a script in R which I am attempting to use to separate several data frames by a certain variable. I am currently using a loop to do this and wondering if I can instead use lapply or a similar function.

The loop essentially takes a data frame, df, which has a column called Time. The time values are in hours and range from 0-48 by multiples of six (which is what the index list contains).

The code should create a new dataframe called data.time.0 consisting of all rows where time = 0, and so on for every value of time.

library(tidyverse)

index = seq(from = 0, to = 48, by = 6)

for (i in index) {
  name = paste("data.time."+i,sep = "")
  currentdf = filter(df,df$time == i)
  assign(name,currentdf)
}

However, I have heard that using assign should be avoided when possible, and I would like to use a vector operation rather than a loop. Is this possible? How would I do it?

Upvotes: 0

Views: 121

Answers (1)

LAP
LAP

Reputation: 6685

A direct translation to lapply() would be

mylist <- lapply(seq(from = 0, to = 48, by = 6), function(x){
  filter(df, df$time == x)
})

names(mylist) <- paste("data.time.", seq(from = 0, to = 48, by = 6),sep = "")

I agree with @Roland's comment, though. It is very likely that there's a simpler approach.

Upvotes: 1

Related Questions