Reputation: 2085
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))
}
Upvotes: 0
Views: 645
Reputation: 886938
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))
}
Upvotes: 3