【发布时间】:2022-02-21 04:22:39
【问题描述】:
我有一个数据框,我想计算所有列的平均值并将其保存到一个新的数据框中。我找到了这个解决方案calculate the mean for each column of a matrix in R 但是,这仅适用于矩阵而不是数据框
structure(list(TotFlArea = c(1232, 596, 708, 1052, 716), logg_weighted_assess = c(13.7765298160156,
13.1822275291412, 13.328376420438, 13.3076293132057, 13.5164823091252
), TypeDwel1.2.Duplex = c(0, 0, 0, 0, 0), TypeDwelApartment.Condo = c(0,
1, 1, 1, 1), TypeDwelTownhouse = c(1, 0, 0, 0, 0), Age_new.70 = c(0,
0, 0, 0, 0), Age_new0.1 = c(0, 0, 0, 0, 0), Age_new16.40 = c(1,
1, 0, 1, 0), Age_new2.5 = c(0, 0, 0, 0, 0), Age_new41.70 = c(0,
0, 0, 0, 0), Age_new6.15 = c(0, 0, 1, 0, 1), LandFreehold = c(1,
1, 1, 0, 1), LandLeasehold.prepaid = c(0, 0, 0, 1, 0), LandOthers = c(0,
0, 0, 0, 0), cluster_K_mean.1 = c(0, 0, 0, 0, 0)), row.names = c("1",
"2", "3", "4", "5"), class = "data.frame")
你能告诉我怎么做吗?
注意:我的数据框可以有 NA 值,应该从平均值计算中排除
【问题讨论】:
-
您可以使用
colMeans,它适用于data.frame/matrix,即colMeans(yourdata, na.rm = TRUE)(假设所有列都是数字) -
colMeans(yourdata, na.rm = TRUE)