Reputation: 33
I need to create a matrix with the columns (Swing, Blues, Contra) and Rows (M, F) using Ht data from a data.frame
.
I need to create a matrix of NA values and then fill the matrix by row using the outcome from each tapply function.
It needs to look like this:
Swing Blues Contra
M 174.6 186.8 194.5
F 177.7 178 180.4
The 2 tapply functions I have are:
tapply(dancenewM$Ht,dancenewM$Type,mean)
tapply(dancenewF$Ht,dancenewF$Type,mean)
sample data:
Sex Type Ht
F Swing 177.9
F Swing 177.5
F Contra 179.6
F Contra 181.3
F Blues 179.7
F Blues 176.3
M Swing 172.7
M Swing 176.5
M Contra 194.6
M Contra 194.4
M Blues 193.4
M Blues 180.2 "))
Any help with this would be greatly appreciated.
Upvotes: 0
Views: 663
Reputation: 887291
We can use tapply
with grouping variables as 'sex' and 'Type' to get the mean
of 'Ht'.
with(df1, tapply(Ht, list(Sex = Sex, Type), FUN= mean))
# Sex Blues Contra Swing
# F 178.0 180.45 177.7
# M 186.8 194.50 174.6
Or we can use data.table
library(data.table)
dcast(setDT(df1), Sex~Type, value.var='Ht', mean)
# Sex Blues Contra Swing
# 1: F 178.0 180.45 177.7
# 2: M 186.8 194.50 174.6
df1 <- structure(list(Sex = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 2L,
2L, 2L, 2L, 2L, 2L), .Label = c("F", "M"), class = "factor"),
Type = structure(c(3L, 3L, 2L, 2L, 1L, 1L, 3L, 3L, 2L, 2L,
1L, 1L), .Label = c("Blues", "Contra", "Swing"), class = "factor"),
Ht = c(177.9, 177.5, 179.6, 181.3, 179.7, 176.3, 172.7, 176.5,
194.6, 194.4, 193.4, 180.2)), .Names = c("Sex", "Type", "Ht"
), class = "data.frame", row.names = c(NA, -12L))
Upvotes: 1