This is my code
col_vec <- vector(length = 11)
my_df <- mtcars
for (i in 1:11) {
col_vec[i]<- glue::glue("col{i}")
colnames(my_df) <- col_vec
}
I want to do this bellow for all columns but I would like to use glue package:
my_df %>% mutate(up_down = as.numeric(col1) - lag(as.numeric(col1),
default = as.numeric(col1)[1]))
I tried this, but it didnt work:
for (i in 1:11) {
my_df %>% mutate(glue::glue("up_down_{i} = as.numeric(col{i}) - lag(as.numeric(col{i}),
default = as.numeric(col{i})[1]))"))
}
The output should give me for each col_*
a column that calculate the difference between rows.
So, I would have 22 columns as a result
We can use
across
more easily without having to assign withglue
on thelhs
. The new columns are automatically added once we modify the.names
-output
If we want to use a
for
loop, it would need assignment (<-
) to original dataset for creating new columns. In addition, we need to evaluate (!!
) while assigning with:=
) (instead ofeval/parse
)-output