Last active
July 12, 2017 17:08
-
-
Save AndrewLJackson/5da491457e9c68fbd8ef9e1842e0d8b0 to your computer and use it in GitHub Desktop.
odd reordering by dplyr::slice
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(tidyverse) | |
# create a list of length 10 with a small dataframe in each entry | |
df <- lapply(1:10,function(x){data.frame(y = 1:5)}) | |
# convert to tbl | |
df_tbl<- bind_rows(df, .id = "id") | |
# pluck out the last entry for each "id" using slice() | |
last_entry <- df_tbl %>% group_by(id) %>% slice(n()) | |
print(last_entry) | |
# note that id = 10 appears second in the list. | |
# instead we have to coerce df_tbl$id to be a factor | |
df_tbl_2 <- bind_rows(df, .id = "id") %>% mutate(id = factor(as.numeric(id))) | |
last_entry_2 <- df_tbl_2 %>% group_by(id) %>% slice(n()) | |
print(last_entry_2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment