2011-08-12 4 views
5

동일하게 정렬 된 데이터 프레임 목록을 가지고 있습니다. 더 구체적으로는 AmeliaII 패키지로 다중 대체를 한 후에 얻는 귀속 된 데이터 프레임입니다. 이제는 구조가 동일하지만 데이터 프레임 전체에서 계산 된 셀의 평균 값을 포함하는 새로운 데이터 프레임을 만들고 싶습니다.동일한 데이터 프레임의 셀에서 통계 (예 : 평균) 계산

나는 순간에 이것을 달성하는 방법은 다음

## do the Amelia run ------------------------------------------------------------ 

a.out <- amelia(merged, m=5, ts="Year", cs ="GEO",polytime=1) 

## Calculate the output statistics ---------------------------------------------- 
left.side <- a.out$imputations[[1]][,1:2] 
a.out.ncol <- ncol(a.out$imputations[[1]]) 

a <- a.out$imputations[[1]][,3:a.out.ncol] 
b <- a.out$imputations[[2]][,3:a.out.ncol] 
c <- a.out$imputations[[3]][,3:a.out.ncol] 
d <- a.out$imputations[[4]][,3:a.out.ncol] 
e <- a.out$imputations[[5]][,3:a.out.ncol] 

# Calculate the Mean of the matrices 
mean.right <- apply(abind(a,b,c,d,e,f,g,h,i,j,along=3),c(1,2),mean) 

# recombine factors with values 
mean <- cbind(left.side,mean.right) 

제가 적용 plyr 등을 사용하여이 일을 더 나은 방법이 있다고 생각하지만, R 신참 I로 정말로 약간 여기에서 길을 잃는다. 이 문제를 해결하는 방법에 대한 제안이 있습니까?

답변

4

여기 Reduceplyr::llply

dfr1 <- data.frame(a = c(1,2.5,3), b = c(9.0,9,9), c = letters[1:3]) 
dfr2 <- data.frame(a = c(5,2,5), b = c(6,5,4), c = letters[1:3]) 

tst = list(dfr1, dfr2) 

require(plyr) 
tst2 = llply(tst, function(df) df[,sapply(df, is.numeric)]) # strip out non-numeric cols 
ans = Reduce("+", tst2)/length(tst2) 

편집을 사용하여 다른 방법입니다. 코드를 상당히 단순화하고 5 줄의 R 코드에서 원하는 것을 성취 할 수 있습니다. 다음은 Amelia 패키지를 사용한 예입니다.

4

내가 제대로 질문을 이해한다면, 이것은 당신에게 먼 길을 가야 :

#set up some data: 
dfr1<-data.frame(a=c(1,2.5,3), b=c(9.0,9,9)) 
dfr2<-data.frame(a=c(5,2,5), b=c(6,5,4)) 
tst<-list(dfr1, dfr2) 
#since all variables are numerical, use a threedimensional array 
tst2<-array(do.call(c, lapply(tst, unlist)), dim=c(nrow(tst[[1]]), ncol(tst[[1]]), length(tst))) 
#To see where you're at: 
tst2 
#rowMeans for a threedimensional array and dims=2 does the mean over the last dimension 
result<-data.frame(rowMeans(tst2, dims=2)) 
rownames(result)<-rownames(tst[[1]]) 
colnames(result)<-colnames(tst[[1]]) 
#display the full result 
result 

HTH를.

+0

감사합니다. 그러나 솔루션과 달리 데이터 프레임은 숫자가 아니라 배열을 사용하기 전에 "스트립"해야하는 두 개의 "요소"열이 있습니다. "혼합 된"데이터 프레임에서도 작동하는 솔루션을 알고 있다면 "모든 것을 얻을 수 있습니다". 하지만 전에 말했듯이, 당신의 솔루션은 이전에 사용했던 솔루션보다 훨씬 간결합니다. – Tungurahua

+0

제가 올바르게 기억한다면, 제가 제공 한 unlist 솔루션은 여전히 ​​대부분 작동 할 것입니다 : 요인들은 수치로 강요 될 것이고, 이것의 평균이 취해질 것입니다 (당신은 안전하게 무시할 수 있습니다). –

1

많은 시도 끝에 여러 데이터 프레임에서 셀의 평균을 계산할 수있는 합리적인 방법을 찾았습니다.

# First create an empty data frame for storing the average imputed values. This 
# data frame will have the same dimensions of the original one 

imp.df <- df 

# Then create an array with the first two dimensions of the original data frame and 
# the third dimension given by the number of imputations 

a <- array(NA, dim=c(nrow(imp.df), ncol(imp.df), length(a.out$imputations))) 

# Then copy each imputation in each "slice" of the array 

for (z in 1:length(a.out$imputations)) { 
a[,,z] <- as.matrix(a.out$imputations[[z]]) 
} 

# Finally, for each cell, replace the actual value with the mean across all 
# "slices" in the array 

for (i in 1:dim(a)[1]) { 
    for (j in 1:dim(a)[2]) { 
imp.df[i, j] <- mean(as.numeric(a[i, j,])) 
    }}