Search code examples
rloopsfor-loopreplicate

Iterate through times argument in rep()-function and store result in new variable in R


I have a dataframe which looks like this:

> df
 1  2  3  4  5  7  8  9 10 11 12 13 14 15 16 
 1  6  0  0  0  0  0  3  0  0  0  0  0  0  1 

I try to replicate the number 1540 by the entries in the df and store them in length(df) new variables. So, this loop should output 16 variables, for example

a1b <- c(1540)
a2b <- c(1540,1540,1540,1540,1540,1540)
...

I tried to solve this, for example, with the code below, but this does not work.

df <- P1_2008[1:16]
for(i in 1:15){
  paste0("a",i,"b") <- rep(c(1540), times = df[i])
}

Does anyone has an idea how to fix this?

Best regards, Daniel

The output of the df is

dput(df)
c(`1` = 1, `2` = 6, `3` = 0, `4` = 0, `5` = 0, `7` = 0, `8` = 0, 
`9` = 3, `10` = 0, `11` = 0, `12` = 0, `13` = 0, `14` = 0, `15` = 0, 
`16` = 1)

Solution

  • Does this help?

    for(i in 1:15){
        assign(paste0("a",i,"b"), rep(c(1540), times = df[i]))
    }
    

    If you want to create a variable name from a string assign() is your friend. The second argument is an object (in this a vector) that is assigned to the variable name given (as a string) in the first argument.