Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete tail of data by group in R

Tags:

r

head

lapply

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.

like image 649
Jdan Avatar asked Jan 26 '26 07:01

Jdan


1 Answers

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.

like image 170
IRTFM Avatar answered Jan 29 '26 01:01

IRTFM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!