1

I'd like to replace certain rows of my variable group with blank. How can I do it without using a for loop? Here is my code. The goal is to code 'group' to be: "A", blank, blank, blank, blank, "A", blank, blank...

group <- rep("A", 20)
var   <- rep("B", 20)

out <- data.frame(group, var)

out$row_num <- seq(1:nrow(out))
    
for (i in 1:nrow(out)) {
   if (out$row_num[i] %% 5 != 1) {
      out$group[i] <- " "
    } 
}
1
  • 1
    Yes, correct. I've fixed it. Thanks! Commented Jun 30, 2020 at 19:48

1 Answer 1

1

These operations are vectorized. So, the replacement can be done without a for loop. Also, from R 4.0, the default option while constructing data.frame is stringsAsFactors = FALSE

out$group[out$row_num %% 5 != 1] <- ' '

Based on the update, if the intention is to replicate

rep(c("A", "", "", "", ""), length.out = 20)
#[1] "A" ""  ""  ""  ""  "A" ""  ""  ""  ""  "A" ""  ""  ""  ""  "A" ""  ""  ""  "" 
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, that's what I intend to replicate.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.