2013-05-09 130 views
2

我有這個data.frame。我需要做的是創建2個額外的列,每個其他列的手段與相同類型的數據。如何計算r中不同列的平均值?

下面是該文件的dput(head())

  structure(list(COLE_CODIGO_COLEGIO = c(182L, 3046L, 3327L, 3418L, 
3459L, 3525L), Utilidad12.1 = c(5.67960793875611e+84, 6.70878394856429e+83, 
3.10783852265787e+84, 1.80000434506295e+84, 7.92256239238555e+84, 
2.6032583906869e+83), genero.x = c(0.581395348837209, 0.525423728813559, 
0.636363636363636, 0.55, 0.488636363636364, 0.63768115942029), 
    Utilidad11.1 = c(1.15336934758534e+73, 3.77916671655328e+72, 
    4.7319512062371e+73, 7.97038534283783e+72, 1.32237182934735e+73, 
    6.55595718179632e+72), genero.y = c(0.527472527472527, 0.616666666666667, 
    0.526315789473684, 0.560975609756098, 0.450704225352113, 
    0.742268041237113), Utilidad10.1 = c(5.09613856124168e+72, 
    5.25727948275145e+71, 1.4350276514895e+72, 7.04968791434072e+72, 
    5.97923875650689e+72, 4.30547735977066e+72), genero.x = c(0.566371681415929, 
    0.315789473684211, 0.571428571428571, 0.578947368421053, 
    0.353658536585366, 0.743243243243243), Utilidad07.1 = c(1.401355333064e+71, 
    1.35282220680438e+71, 9.87359187347488e+71, 1.89236591312778e+72, 
    1.18195124980311e+73, 5.99279404969151e+70), genero.y = c(0.534883720930233, 
    0.522727272727273, 0.5, 0.560975609756098, 0.411764705882353, 
    0.714285714285714), Utilidad06.1 = c(4.47939696971958e+72, 
    2.91946645871643e+72, 3.16785158272574e+72, 1.16889985482301e+74, 
    5.83958109398712e+74, 5.37640536403147e+71), genero = c(0.5, 
    0.6, 0.357142857142857, 0.5, 0.422680412371134, 0.695652173913043 
    )), .Names = c("COLE_CODIGO_COLEGIO", "Utilidad12.1", "genero.x", 
"Utilidad11.1", "genero.y", "Utilidad10.1", "genero.x", "Utilidad07.1", 
"genero.y", "Utilidad06.1", "genero"), row.names = c(NA, 6L), class = "data.frame") 

我的意思是我想名爲「MeanUtilidad」,也就是在它取名爲「Utilidad」每隔一列的平均值創建列。還有一個名爲「Meangenero」的列,其中包含名稱爲「genera」的其他變量的均值。

我希望我已經足夠表達我的問題了。

我試過使用下面的代碼Semestre1["UProm"]<-apply(Semestre1 [ ,2:dim(Semestre1)[2]],1,mean, na.rm=T)但它考慮到每列的意思,我不能想出一種方法來選擇每個特定的列。

回答

4

你可以這樣做:

dat$MeanUtilidad <- rowMeans(dat[grep("Utilidad", names(dat), value = TRUE)]) 
dat$MeanGenero <- rowMeans(dat[grep("genero", names(dat), value = TRUE)]) 
+0

這並獲得成功非常感謝! – MJAS 2013-05-10 00:11:17

1

rowMeans將輸入強制到矩陣。你可以使用Reduce(`+`, list)

如對rowMeans

nUtilidad <- grep("Utilidad", names(dat), value = TRUE) 
nGenero <- grep("genero", names(dat), value = TRUE) 

dat$MeanUtilidad <- Reduce(`+`, dat[nUtilidad])/length(nUtilidad) 
dat$MeanGenero <- Reduce(`+`, dat[nGenero])/length(nGenero) 

標杆這個小例子

library(microbenchmark) 
microbenchmark(Reduce(`+`,dat[nUtilidad])/length(nUtilidad), rowMeans(dat[nUtilidad])) 
## Unit: microseconds 
##           expr  min  lq median  uq  max neval 
## Reduce(`+`, dat[nUtilidad])/length(nUtilidad) 75.561 77.6105 79.2025 80.4055 451.967 100 
##      rowMeans(dat[nUtilidad]) 178.477 179.9305 180.9955 182.6255 321.482 100