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?
split(df, df$time)?split()and get a list than useassign().split()existed. So if I dosplit(df,df$time)<-paste("data.time.", seq(from = 0, to = 48, by = 6),sep = "")this will give me a list containing all the data frames I want?splitinto a new variable:split_df <- split(df,df$time). That new variable will be a list of data frames. I believe the default names will be the values fromdf$time(as strings).