-1

I would like to convert this code into FOR LOOP but I met mistakes and I could not finish it. Thank you for your help!


PM2.52018 <- data_df[which(data_df$type=='PM2.5'),]
PM102018<- data_df[which(data_df$type=='PM10'),]
SO2 <- data_df[which(data_df$type=='SO2'),]
CO <- data_df[which(data_df$type=='CO'),]
NO2 <- data_df[which(data_df$type=='NO2'),]
O3 <-  data_df[which(data_df$type=='O3'),]
  • 1
    There is a lot to learn from this question and all potential answers. One thing: we can subset data.frames with logical indexes too. So `O3 <- data_df[which(data_df$type=='O3'),]` can be replaced by the simpler `O3 <- data_df[ data_df$type=='O3' , ]` – GuedesBF Feb 07 '22 at 20:03
  • If you want to convert your entire dataframe to vectors named with the column heading. You can use this: `dframe <- data.frame (Gender = c("2","2","1","2"), AgeG = c("3","1","4","2")); for (name in names(dframe)){ assign(name, dframe[name]); }` I would not consider this idiomatic R code. – typewriter Feb 07 '22 at 20:16
  • We can only help so much without a proper reproducible example. Plase share at least a subset of the `data_df` object with `dput(data_df)` or `dput(head(data_df))` – GuedesBF Feb 07 '22 at 20:20

1 Answers1

3

We do not need a for loop here. Just use split. After that, we can rename the individual data.frames as desired. This will get us a list of dataframes, which is usually much better than keeping all this likely related dataframes in the global environment

my_list <- split(data_df, data_df$type)
GuedesBF
  • 8,409
  • 5
  • 19
  • 37