I'm using dplyr
to transform a large data frame, and I want to store the DF's most recent date + 1 as a value. I know there's easier ways to do this by breaking up the statements, but I'm trying to do it all with one pipe statement. I ran into something and I'm not sure why R defaults that way. Example:
Day <- seq.Date(as.Date('2017-12-01'), as.Date('2018-02-03'), 'day')
Day <- sample(Day, length(Day))
ID <- sample(c(1:5), length(Day), replace = T)
df <- data.frame(ID, Day)
foo <- df %>%
arrange(desc(Day)) %>%
mutate(DayPlus = as.Date(Day) + 1) %>%
select(DayPlus) #%>%
#slice(1)
foo <- foo[1,1]
When I run this code, foo
becomes a value equal to 2018-02-04
as desired. However, when I run the code with slice
uncommented:
foo <- df %>%
arrange(desc(Day)) %>%
mutate(DayPlus = as.Date(Day) + 1) %>%
select(DayPlus) %>%
slice(1)
foo <- foo[1,1]
foo
stays as a dataframe. My main question is why foo
doesn't become a value in the second example, and my second question is if there's an easy way get the "2018-02-04" as a value stored as foo
all from one dplyr
pipe.
Thanks