2016-09-08 11 views
1

私のデータフレーム内のIは、のすべての値にわたる平均、標準偏差および変動の共効率を計算しようとしている(FID_BoundaNAMEDESCRIPTIO & SOVEREIGNTによって定義される)の下各列はcrNで始まります。Rのddply行要約統計

structure(list(FID_Bounda = 0:7, NAME = c("Bedfordshire", "Berkshire", 
"Bristol", "Buckinghamshire", "Cambridgeshire", "Cheshire", "Derbyshire", 
"Devon"), DESCRIPTIO = c("Ceremonial County", "Ceremonial County", 
"Ceremonial County", "Ceremonial County", "Ceremonial County", 
"Ceremonial County", "Ceremonial County", "Ceremonial County" 
), SOVEREIGNT = c("England", "England", "England", "England", 
"England", "England", "England", "England"), crN1 = c(61.944107636, 
38.769347117, 0.810167027, 63.721241962, 191.046323469, 81.467146994, 
61.65529268, 288.751788714), crN10 = c(60.33595964, 38.326639788, 
0.834289164, 63.009539538, 185.25772542, 82.936101454, 61.985178493, 
304.951827268), crN100 = c(53.385110882, 33.530058107, 0.739041324, 
55.601839364, 165.604271128, 76.386014559, 55.591194915, 284.739586188 
), crN1000 = c(58.397452282, 37.277298648, 0.820739862, 61.716749153, 
175.436497697, 82.461823706, 61.762203751, 321.414544333)), .Names = c("FID_Bounda", 
"NAME", "DESCRIPTIO", "SOVEREIGNT", "crN1", "crN10", "crN100", 
"crN1000"), row.names = c(NA, 8L), class = "data.frame") 

私は、これらの値を導出するcookbook-rに概説されたコードを使用しようとしました:

正しく crN列の合計Nをカウントしますが、それは行ごとに同じ平均、SDおよびSEを与える
cdata <- ddply(uadt, c("FID_Bounda","NAME","DESCRIPTIO","SOVEREIGNT"), summarise, 
       N = length(grep("crN", names(uadt), value = T)), 
       mean = mean(grep("crN", names(uadt), value = F)), 
       sd = sd(grep("crN", names(uadt), value = F)), 
       se = sd/sqrt(N) 
) 
cdata 

。実際のデータセットには、すべて同じ名前パターンのcrNnumberを持つ1000列があるため、問題がどこにあるかについての助けとなります。

答えて

3

これは完璧な答えではありませんが、より最新のツールを使用する価値があるかもしれません(私の答えはtidyrを使用しないため、しかし、私はかかるだろうなアプローチは次のとおりです。

library(reshape2) 
madt <- melt(uadt, 
      id.vars = c("FID_Bounda", "NAME", 
         "DESCRIPTIO", "SOVEREIGNT")) 
library(dplyr) 
cdata <- summarise(group_by(madt, 
          FID_Bounda, NAME, 
          DESCRIPTIO, SOVEREIGNT), 
        N = n_distinct(variable), 
        mean = mean(value), 
        sd = sd(value), 
        se = sd/sqrt(N)) 

これはあなたが望むものである正しい出力

1

料理の例ではない行、全体の列ダウン平均値と他の関数を計算さを生み出すん。

この使用してベースRを達成する方法は次のとおりです。

functions <- list(length, mean, sd) 

d <- lapply(functions, function(y) { 
    apply(uadt, 1, function(x) y(as.numeric(x[5:8]))) 
}) 

calc <- as.data.frame(do.call(cbind, d)) 
names(calc) <- c("N", "mean", "sd") 

cdata <- cbind(uadt[1:4], calc) 
cdata$se <- cdata$sd/sqrt(cdata$N) 

あなたはより多くの数値列を持っている場合は、単純に5区間変更:適切8。