1

In many answers here in SO, posters advise to avoid using assign() to create new variables inside a loop, like this code reproduced here from this question:

myDf <- mtcars
splitVar <- factor(myDf$gear)
levelsVar <- levels(splitVar)
splitDataFrame <- split(myDf, splitVar)
for (i in 1:length(levelsVar)) {
  assign(paste0("newDataFrameGear", levelsVar[i]), data.frame(splitDataFrame[i]))
}
ls(pattern = "^newData")

This post explains why it is considered bad practice, but what other options are available to prevent this?

Community
  • 1
  • 1
Paulo MiraMor
  • 1,582
  • 12
  • 30

1 Answers1

1

Why not just keep using the original list, but assign the names you want:

names(splitDataFrame) <- paste0("newDataFrameGear",
                                as.character(levels(splitVar)))
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360