0

Is there a way to simplify this code using a loop?

VariableList <- c(v0,v1,v2, ... etc)

National_DF <- df[,VariableList]
AL_DF <- AL[,VariableList]
AR_DF <- AR[,VariableList]
AZ_DF <- AZ[,VariableList]
... etc

I want the end result to have each as a data frame since it will be used later in the model. Each state such as 'AL', 'AR', 'AZ', etc are data frames. The v{#} represents an out of place variable from the RAW data frame. This is meant to restructure the fields, while eliminating some fields, for preparation for model use.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
Andrew Hicks
  • 572
  • 1
  • 6
  • 19
  • 1
    Please edit your post to make a Minimal Reproducible Example. See https://stackoverflow.com/questions/5963269 . You _must_ include some sample data; 4-10 lines is usually enough. Edit your post to include the results of `dput(head(df))`, if `df` is where your data is. Include a sample of what you want the output to look like. Don't include images or links to outside data source. We want to help you, but you've got to work with us. – David T May 28 '20 at 03:08
  • I can see this runing with sapply, but you have to provide an better exemple how you dada is strutured for ```v{#}``` – FrakTool May 28 '20 at 03:08
  • Don't add `rstudio` tag if your question is not specifically about RStudio i.e the IDE. – Ronak Shah May 28 '20 at 03:13
  • Ronak, sorry...Still learning. Will try and be more aware moving forward. – Andrew Hicks May 28 '20 at 03:23

1 Answers1

2

Continuing the answer from your previous question, we can arrange the data in the same lapply call before creating dataframes.

VariableList <- c('v0','v1','v2')

data <- unlist(lapply(mget(ls(pattern = '_DF$')), function(df) {
    index <- sample(1:nrow(df), 0.7*nrow(df))
    df <- df[, VariableList]
    list(train = df[index,], test = df[-index,])  
}), recursive = FALSE)

Then get data in global environment :

list2env(data, .GlobalEnv)
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • 1
    Ronak, thanks again! I had to do some alterations to my prequel code but I was able to get this to simplify both questions based off you feedback. Thank!!! – Andrew Hicks May 28 '20 at 03:22