0

How can I create a sequence of columns (let's say X1, X2, ..., X100) with their value dependent on column index (1-100) with or (ideally) without using a for loop?

Below is my attempt with for loop (it's not working - I think it has something to do with the usage of paste to create the names of columns. But I believe it describes well I would like to achieve.

data <- runif(10)
data <- as_tibble(data)
for (i in 1:100){
  data <- data %>% mutate(paste('X', i, sep = '') = (value > 0.01 * i))
}

1 Answer 1

3

We can use map with !!

library(tidyverse)
map(1:100, ~ data %>% 
              transmute(!! paste0("X", .x) := value > 0.01 * .x)) %>% 
   bind_cols(data, .)

Or with for loop

for (i in 1:100){
     data <- data %>% 
                  mutate(!! paste('X', i, sep = '') := (value > 0.01 * i))
 }
Sign up to request clarification or add additional context in comments.

2 Comments

That's a cool expression! Could you explain the use of double exclamation mark as I can't find what's its meaning?
@jakes The assignment operator is := is used in data.table, but it is introduced recently in dplyr

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.