0

I am trying to create a new variable which will correspond to a dataframe. The function "assign" does not work because the dataframe is too complex (it uses dplyr functions from a parent dataframe).

Just to try out I ran the following code:

Fam <- paste0("Fam", seq(13,53,2))
for(i in Fam){
  i <- seq(1,5,1)
}

There is no error popping up but I would like to have each variable created on the environment (Fam13, Fam15, Fam17, etc.)

When I run my code there is no error either but no variables are created.

for (i in Fam){
  i <- CPS_reduced %>%
    filter(SOC_Fam == i)%>%
    select(Occupation, Share.of.population.2002, Share.of.population.2018, Share.of.population.2034, Share.2034.with.robots)

I have also tried to create a function to do this and then do something like

Fam <- function(i)
paste0("Fam",i) <- CPS_reduced %>%
filter(SOC_Fam ==i)
...

lapply(seq(13,53,2), function(i))

However, this gives the error that I can't assign something to paste0.

Thank you for your help!

Gautam
  • 2,597
  • 1
  • 28
  • 51
InesGuardans
  • 129
  • 10
  • 2
    You're looking for `?assign` but see this first [Why is using assign bad?](https://stackoverflow.com/questions/17559390/why-is-using-assign-bad) – A. Suliman Aug 26 '19 at 17:29
  • 2
    Use a named list instead: `df_list <- split(CPS_reduced, CPS_reduced$SOC_Fam)`. – Parfait Aug 26 '19 at 17:47
  • Can you post what you want the end result to look like? – Monk Aug 26 '19 at 17:53
  • 1
    I would strongly encourage you to avoid creating a bunch of free floating variables in your workspace. It's much more difficult to work list. Using a named list for related objects makes things so much easier in R. – MrFlick Aug 26 '19 at 18:12
  • @MrFlick but you suggest that i have a list where each variable is a dataframe? – InesGuardans Aug 27 '19 at 18:31

0 Answers0