-2

I want to know how to make a loop in R. I show a very simple example of a code below,

Test_A <- Test %>% mutate (A = 1)
Test_B <- Test %>% mutate (B = 1)
Test_C <- Test %>% mutate (C = 1)
Test_D <- Test %>% mutate (D = 1)

I want to make a loop for this code and make it more simple because this code is too repetitive. Do anyone have suggestion for me?

wibeasley
  • 3,613
  • 1
  • 26
  • 47
yuki
  • 1
  • 2
    You'll likely get a recommendation or two that suggests the use of `assign`. I discourage this behavior, it typically *slows down* how you work on your project, and makes for inefficient code. Consider keeping it as a "list of frames", see https://stackoverflow.com/a/24376207/3358272 – r2evans Aug 14 '20 at 19:17
  • 2
    In which case, `lapply(LETTERS[1:4], function(cn) { Test[[cn]] – r2evans Aug 14 '20 at 19:19
  • Please take a tutorial to learn basics for how to program R. This is a very general and very basic question that would be explained by any tutorial. And the answer is probably that you don't want to use a loop, you want to use a vector operation. But there is no way to tell from your example what you are trying to do or why. – Adam Sampson Aug 14 '20 at 19:24

1 Answers1

1

Let's say you have a sample data.frame like

set.seed(5)
vals <- LETTERS[1:5]
Test <- data.frame(Map(function(...) sample(0:1, 10, replace=T), vals))

Then it would be better to keep these different datasets in a list rather than have them as separate variables in your namespace. You could do

Outs <- Map(function(x) Test %>% mutate (!!x := 1), vals)

Then you can get at the data with Outs[["A"]], Outs[["B"]], etc...

MrFlick
  • 163,738
  • 12
  • 226
  • 242
  • I nearly posted the same thing. The double bang and `:=` operator might benefit from a little exposition here given the presumed level of the OP's familiarity with the language. – Allan Cameron Aug 14 '20 at 19:31
  • Hi MrFlick, thank you for your kind comment. It is my bad that the sample code I shown here was not actually what I want to do. I really want to make a loop for different strings. I appreciate your help! – yuki Aug 14 '20 at 19:50