2012-12-04 56 views
0

我有一個簡單的問題,我無法用for循環解決。 我每次在我的for循環內計算並保存列的平均值。添加值而不是覆蓋for循環內

在第一個循環中,均值被保存到變量中。但在第二個循環中,column2的平均值將替換column1的平均值。這是一個非常基本的問題,但我不知道該怎麼做。

#read.table(file1) 
for (x in 1:100){ 
f <- mean(file1[,x]) 
} 

我要救的平均值爲1個變量的所有列(假設它被稱爲「F」)。

f <- c(meancol1, meancol2, meancol3... meancol100) 

任何想法?

回答

2

更簡單的你可以使用colMeans函數。這裏有一個例子

> set.seed(001) # Generating some random data 
> file1 <- data.frame(matrix(rnorm(50, 100, 5), ncol=5)) 
> file1 # this is how the artificial data.frame should look like 
      X1  X2  X3  X4  X5 
1 96.86773 107.55891 104.59489 106.79340 99.17738 
2 100.91822 101.94922 103.91068 99.48606 98.73319 
3 95.82186 96.89380 100.37282 101.93836 103.48482 
4 107.97640 88.92650 90.05324 99.73097 102.78332 
5 101.64754 105.62465 103.09913 93.11470 96.55622 
6 95.89766 99.77533 99.71936 97.92503 96.46252 
7 102.43715 99.91905 99.22102 98.02855 101.82291 
8 103.69162 104.71918 92.64624 99.70343 103.84266 
9 102.87891 104.10611 97.60925 105.50013 99.43827 
10 98.47306 102.96951 102.08971 103.81588 104.40554 
> colMeans(file1) # this part computes the means for each column without a 'for' loop 
     X1  X2  X3  X4  X5 
100.66101 101.24422 99.33163 100.60365 100.67068 

看看?colMeans

如果你有非數字列可以autotically跳過它們使用sapplycolMeans例如:

set.seed(001) # Generating some random data 
file1 <- data.frame(matrix(rnorm(50, 100, 5), ncol=5)) 
# Creating three columns with non-numeric data 
factors <- data.frame(matrix(sample(letters, 30, TRUE), ncol=3)) 

file1 <- cbind(factors, file1) # this is your data.frame 
colnames(file1) <- paste0('Col.', 1:ncol(file1)) # set some colnames 
file1 # this is the data.frame to work with 
> colMeans(file1[sapply(file1, is.numeric)])# colmeans for only those numeric cols 
    Col.4  Col.5  Col.6  Col.7  Col.8 
100.65027 101.52467 102.04486 99.14944 100.23847 
+0

現在這個工作很好,但我在這裏仍然有點問題。我的數據的前3列不是數字。 colMeans函數正在考慮所有列爲數字,我可以排除前3個colmuns嗎?還是我需要創建一個由數字組成的新文件?謝謝 – Error404

+0

你先生,都很親切:帽子: 非常感謝:) – Error404

0

你不需要循環。

f<-apply(file1,2,mean) 
+1

或這種特殊情況下,使用更快的'colMeans'功能。 – flodel

+0

這一個也工作,謝謝。然而,正如我在本頁面向我們的朋友提及的那樣。第一列不是數字。我能否以某種方式解僱他們? – Error404

+1

例如,如果前三列不是數字,您可以編寫apply(file1 [, - (1:3)],2,mean) –