Anshuman
Anshuman

Reputation: 49

Using dynamic naming while adding new columns to tibble

While using bind_cols () or add_column, I am not able to use the paste/paste0 to name the columns dynamically inside a loop.

for (i in 1:10){
abc %>%
add_column(paste0("new",i) = 1:6)
} 

The above code gives an error. How do I name new columns dynamically Inside a loop.

Upvotes: 2

Views: 697

Answers (2)

IRTFM
IRTFM

Reputation: 263362

The solution offered so far is going to be somewhat fragile and ultimately useless, since it errors out if the number of rows of abc is not equal to the length of the value vector on the RHS of :=. Instead one should use code that creates or selects values that match the first dimension of the data structure. And equally important : the value of that result needs to be assigned back to abc. Otherwise nothing durable happens.

abc <- data.frame(a=1:3)
for (i in 1:10){
   abc <- abc %>%
            add_column(!! paste0("new",i) := 1:nrow(.))
} 

Upvotes: 2

Anshuman
Anshuman

Reputation: 49

Using :=

for (i in 1:10){
abc %>%
add_column(!! paste0("new",i) := 1:6)
} 

Upvotes: 0

Related Questions