r - Most efficient way to create matrix of averages -
this question has answer here:
very basic question here! on 10 x 2 data frame, want calculate average of each column , place result in new 1 x 2 matrix.
colmeans
calculates averages, places result in 2 x 1 vector. attempting transpose vector gives error message "error in transpose(averagex) : l must list."
as workaround, created empty 1 x 2 matrix (filled nas), used rbind
merge averages vector empty matrix, , deleted nas.
it works bet same 2 lines of code rather four. have better way achieve this? help.
df <- data.frame(price = c(1219, 1218, 1220, 1216, 1217, 1218, 1218, 1207, 1206, 1205), xxx = c( 1218, 1218, 1219, 1218, 1221, 1217 , 1217, 1216, 1219, 1216)) average <- colmeans(df, na.rm = true) #result vector => turn 1xm matrix averagematrix <- matrix(nrow = 1, ncol = 2) averagematrix <- rbind(averagematrix, average) averagematrix<- averagematrix[-1, , drop = false]
edit: @akrun creating matrix of averages , creating average each column of matrix similar yet technically different issues, hence in opinion not duplicate. question expresses knew how calculate average each column of matrix, , wanted more efficient way store result matrix, simple issue not addressed in other question.
you can named matrix of column means transposing result colmeans()
, because (from help(t)
)
when x vector, treated column, i.e., result 1-row matrix.
t(colmeans(df, na.rm = true)) # price xxx # [1,] 1214.4 1217.9
Comments
Post a Comment