Reputation: 25
I have a data frame with three columns (Mouse, Day, vol). I am trying to use dplyr to create a new dataframe to extract the last "Day" value for each mouse and the corresponding "vol" for that mouse. I am able to use the max function to get the right "Day" but am having trouble grabbing the matching "vol". Any help is appreciated. Below is my dataframe dput and the code I am trying to assemble.
final_meas <- ddply(df, "Mouse", summarise,
final_day = max(Day),
final_vol =
)
If there is a better way to do this please let me know.
Data frame dput()
structure(list(Mouse = c("CF1", "CF2", "CG1", "CG2", "CG3", "CO1",
"CO2", "CU1", "CY1", "CF1", "CF2", "CG1", "CG2", "CG3", "CO1",
"CO2", "CU1", "CY1", "CF1", "CF2", "CG1", "CG2", "CG3", "CO1",
"CO2", "CU1", "CY1", "CF1", "CF2", "CG1", "CG2", "CG3", "CO1",
"CO2", "CF2", "CG1", "CG2", "CG3", "CO1", "CF2", "CG1", "CG2",
"CG3", "CO1", "CF2", "CG1", "CG2", "CG3", "CO1", "CF2", "CG1",
"CG2", "CG3", "CO1", "CF2", "CG1", "CG2", "CG3", "CO1", "CF2",
"CG1", "CG2", "CG3", "CO1"), Day = c(11, 11, 11, 11, 11, 11,
11, 11, 11, 14, 14, 14, 14, 14, 14, 14, 14, 14, 16, 16, 16, 16,
16, 16, 16, 16, 16, 21, 21, 21, 21, 21, 21, 21, 26, 26, 26, 26,
26, 28, 28, 28, 28, 28, 30, 30, 30, 30, 30, 32, 32, 32, 32, 32,
35, 35, 35, 35, 35, 38, 38, 38, 38, 38), vol = c(45.9675, 36.1712655,
87.777976, 14.29754, 14.2842745, 22.989735, 19.3821875, 56.216752,
71.251488, 0.5, 44.6299425, 119.070536, 26.82875, 21.999132,
71.801216, 0.5, 255.874619, 137.720968, 0.5, 21.5552, 115.16616,
33.132848, 17.619264, 51.185368, 0.5, 212.1728, 340.5686, 0,
0.5, 75.154122, 76.0952875, 0.5, 107.208528, 0, 0.5, 63.5839875,
233.4784, 0.5, 74.6727445, 0.5, 55.7932375, 361.3029455, 0, 88.297668,
0.5, 38.0849105, 228.4934, 0.5, 136.778328, 0.5, 0.5, 186.7279545,
0.5, 178.4032435, 0.5, 0, 186.7279545, 0.5, 89.4645, 0.5, 0,
186.7279545, 0.5, 169.296399)), row.names = c(NA, -64L), class = c("tbl_df",
"tbl", "data.frame"))
Upvotes: 0
Views: 23
Reputation: 4151
Here is one approach using the tidyverse
library(tidyverse)
df_example %>%
group_by(Mouse) %>%
mutate(max_day = max(Day),
max_vol = if_else(Day == max(Day),vol,NA_real_)) %>%
fill(max_vol,.direction = "downup")
Upvotes: 1