심지어 더 간단하면 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
내부 sapply
를 사용 autotically을 건너 뛸 수 있습니다 ?colMeans
에서보세요이다 :
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
이제 위대하게 작동하지만 여기에도 약간의 문제가 있습니다. 내 데이터의 처음 3 열은 숫자가 아닙니다. colMeans 함수는 모든 열을 숫자로 간주합니다. 예를 들어 첫 번째 3 개의 colmun을 제외 할 수 있습니까? 또는 숫자로만 이루어진 새로운 파일을 만들 필요가 있습니까? 감사합니다 – Error404
당신은 선생님, 매우 친절합니다 : 모자 : 많은 감사 :) – Error404