sdaniel24
sdaniel24

Reputation: 25

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)

Upvotes: 1

Views: 134

Answers (3)

Georgery
Georgery

Reputation: 8117

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.

Upvotes: 1

Yuriy Saraykin
Yuriy Saraykin

Reputation: 8880

use tidyverse

library(tidyverse)
df <- read.table(text = "1  6  0  0  0  0  0  3  0  0  0  0  0  0  1", header = F)
out <- map(df, ~rep(1540, .x)) %>% purrr::set_names(., paste0("a", seq_along(df), "b"))
list2env(out, envir = .GlobalEnv)
#> <environment: R_GlobalEnv>

Created on 2020-09-30 by the reprex package (v0.3.0)

Upvotes: 1

cookesd
cookesd

Reputation: 1336

Assign is the right choice, but the answer above has it sligtly backwards. You should provide the text you want for your variable as the first argument and the desired value as the second, so this should work.

for (i in 1:16){assign(paste0('a',i,'b'),rep(1540,i))}

Upvotes: 0

Related Questions