I have a data frame similar to
df <- data.frame(group=c("a", "b"), value=1:16,trim=rep(1:2))
I am trying to figure out how I can remove the last rows of each group. The number of rows to remove from each group is defined in the "trim" variable.
I have figured out how to remove a specified number of of rows from all groups using
x<-do.call("rbind", lapply(split(df, df$group), head,-2))
However, I can't seem to figure how I'd remove the number of rows from a group specified in the "trim" column. In other words, I would like group a to have the last row trimmed and group b the last 2 rows trimmed.
Try to pull first value within group:
x<-do.call("rbind", lapply(split(df, df$group), function(d) head(d,-d$trim[1]) ) )
Normally I test my answers but doing this from an iPhone on a bouncing train.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With