4

For example, I want to assign 1 to a, b, c, ..., z. I have to type,

a <- 1
b <- 1
c <- 1
...
z <- 1

How can I type one line and assign all values to variables?

27182818
  • 91
  • 1
  • 2
  • 9
  • 6
    `a <- b <- c <- z <- 1`; this will work just fine, they will all be separate variables and not cause you the same issues as, say, python would. – duckmayr Oct 04 '18 at 09:12
  • 1
    You can iterate with `apply` family of functions and use `assign`: `sapply(letters, assign, 1, envir = parent.frame())` – pogibas Oct 04 '18 at 09:16
  • @PoGibas Great suggestion, especially if you're assigning to more than three or four variables. – duckmayr Oct 04 '18 at 09:17
  • @duckmayr and @Ronak perhaps this question could be considered different than the one linked as duplicate, [Mass variable declaration and assignment in R?](https://stackoverflow.com/questions/13384593/mass-variable-declaration-and-assignment-in-r). That is, in that other question there are only 5 variables to assign. Would it be reasonable to considered this question different as @duckmayr points out because the number of variables the OP is trying to assign here is much more than you would reasonably want to type in a chain of `<-` assignments? – krads Oct 04 '18 at 09:43
  • @krads Reasonable suggestion; I hadn't considered that aspect at the time I cast a close vote -- sometimes volume can make seemingly identical tasks different. I'll add a reopen vote, though I'll say I can't unilaterally remove the duplicate marking. – duckmayr Oct 04 '18 at 09:46

2 Answers2

2

You might try simply:

for (x in letters) assign(x,1)
krads
  • 1,350
  • 8
  • 14
1

A different approach, without the use of assign: See here

my_list <- as.list(paste(letters[1:3]))
names(my_list) <- paste(letters[1:3])

library(purrr)
map(my_list, function(x) {x <- 1
                          x})

$`a`
[1] 1

$b
[1] 1

$c
[1] 1
RLave
  • 8,144
  • 3
  • 21
  • 37