1

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)
sdaniel24
  • 25
  • 5

3 Answers3

1

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.

Georgery
  • 7,643
  • 1
  • 19
  • 52
  • Hi Georgery, this does exactly what I need, thank you very much for this :) – sdaniel24 Sep 30 '20 at 12:01
  • Welcome. To be honest, I think it's very likely that creating all those vectors is eventually not an optimal solution to your actual problem. But that would be a different question then. – Georgery Sep 30 '20 at 12:08
1

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)

Yuriy Saraykin
  • 8,390
  • 1
  • 7
  • 14
0

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))}
cookesd
  • 1,296
  • 1
  • 5
  • 6
  • I corrected my answer. However, if you see a mistake in an answer, you should comment on the answer and point out the mistake - not post the very same answer just corrected. – Georgery Sep 30 '20 at 11:53
  • Hey, thank you for your response, your code outputs a1b = 1540 and a2b= 1540 1540 and so on.... but i need 1540 to be repilcated by the entries of the df (so 1, 6, 0...) and not (1,2,3,4...). vg daniel – sdaniel24 Sep 30 '20 at 11:56
  • @Georgery sorry about that. I'll do it in the future. – cookesd Sep 30 '20 at 12:02