[R] by group

Rasmus Liland
Tue, 02 Nov 2021 00:55:14 -0000

Dear Val,

also consider using reshape2::dcast

	dat <- structure(list(Year = c(2001L,
	2001L, 2001L, 2001L, 2001L, 2001L,
	2002L, 2002L, 2002L, 2002L, 2002L,
	2002L, 2003L, 2003L, 2003L, 2003L,
	2003L, 2003L), Sex = c("M", "M", "M",
	"F", "F", "F", "M", "M",
"M", "F", "F",
	"F", "M", "M", "M", "F",
"F", "F"), wt 	c(15L, 14L, 16L, 12L, 11L, 13L, 14L,
	18L, 17L, 11L, 15L, 14L, 18L, 13L, 14L,
	15L, 10L, 11L)), class = "data.frame",
	row.names = c(NA, -18L))

	reshape2::dcast(data=dat,
	                formula=Year~Sex,
	                value.var="wt",
	                fun.aggregate=mean)

yielding

	  Year        F        M
	1 2001 12.00000 15.00000
	2 2002 13.33333 16.33333
	3 2003 12.00000 15.00000

Best,
Rasmus