Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to mutate and create many new variables with one line of code?

Tags:

r

dplyr

I have something like:

df<-data.frame(group=c(1, 1, 1, 1,1,2, 2, 2, 2), 
               date=c("2000-01-01 11:00:00", "2000-01-03 11:00:00", "2000-01-04 11:20:00", "2000-01-04 14:20:00", "2000-01-05 11:40:00", "2000-01-09 12:20:00", "2000-01-09 13:20:00", "2000-01-10 12:20:00", "2000-01-12 16:20:00"))
  group                date
1     1 2000-01-01 11:00:00
2     1 2000-01-03 11:00:00
3     1 2000-01-04 11:20:00
4     1 2000-01-04 14:20:00
5     1 2000-01-05 11:40:00
6     2 2000-01-09 12:20:00
7     2 2000-01-09 13:20:00
8     2 2000-01-10 12:20:00
9     2 2000-01-12 16:20:00

I'd like to make many columns indicating 24 hours after the date, 48 hours, etc. (for instance):

df%>%mutate(first=date+86400, second=date+172800, third=date+259200) 

etc. etc. where I'm adding a day in seconds, but this is very time consuming (if I want hundreds of columns). I'm assuming there's a way to do this iteratively.

Thanks,

like image 411
biostatguy12 Avatar asked Nov 29 '25 20:11

biostatguy12


1 Answers

If we can make use of the english package, the column names can be generated while the values are generated with lapply

library(english)
df$date <- as.POSIXct(df$date)
df[as.character(ordinal(1:3))] <- lapply(1:3, function(x) df$date + 86400 * x)

It can be done in a single line of code with as.POSIXct conversion in the loop, but we would be unnecessarily doing conversion multiple times (Not all one-liners are efficient)


Or with purrr

library(purrr)
library(dplyr)
map_dfc(1:3, ~ tibble(!! as.character(ordinal(.x)) := df$date + 86400 * .x)) %>%
   bind_cols(df, .)
# group                date               first              second               third
#1     1 2000-01-01 11:00:00 2000-01-02 11:00:00 2000-01-03 11:00:00 2000-01-04 11:00:00
#2     1 2000-01-03 11:00:00 2000-01-04 11:00:00 2000-01-05 11:00:00 2000-01-06 11:00:00
#3     1 2000-01-04 11:20:00 2000-01-05 11:20:00 2000-01-06 11:20:00 2000-01-07 11:20:00
#4     1 2000-01-04 14:20:00 2000-01-05 14:20:00 2000-01-06 14:20:00 2000-01-07 14:20:00
#5     1 2000-01-05 11:40:00 2000-01-06 11:40:00 2000-01-07 11:40:00 2000-01-08 11:40:00
#6     2 2000-01-09 12:20:00 2000-01-10 12:20:00 2000-01-11 12:20:00 2000-01-12 12:20:00
#7     2 2000-01-09 13:20:00 2000-01-10 13:20:00 2000-01-11 13:20:00 2000-01-12 13:20:00
#8     2 2000-01-10 12:20:00 2000-01-11 12:20:00 2000-01-12 12:20:00 2000-01-13 12:20:00
#9     2 2000-01-12 16:20:00 2000-01-13 16:20:00 2000-01-14 16:20:00 2000-01-15 16:20:00
like image 195
akrun Avatar answered Dec 01 '25 12:12

akrun