Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201839

Looping and concatenating based on a condition in R

$
0
0

I'm new to R and still struggling with loops.

I'm trying to create a loop where, based on a condition (variable_4 == 1), it will concatenate the content of variable_5, separated by comma.

data1$new_var<- ""

for(i in 2:10){

  variable_4 <- paste0("flag_", i)
  variable_5 <- paste0("agent_", i)

  data1 <- data1 %>%
    mutate(!! new_var = case_when(variable_4 == 1,paste(new_var, variable_5, sep=",")))
}

I've created new_var in a previous step because the code was giving me an error that the variable was not found. Ideally, the loop will accumulate the contents of variable_5, only if variable_4 is equal 1 and the result would be big string, separate by comma.


Viewing all articles
Browse latest Browse all 201839

Trending Articles