zjsty 你的代码没写好。首先你的colSums(data)在循环过程中会变,其次colSums(data)返回的是一个数值向量,长度为列数。用循环的话建议新建一个data2用以储存数据,也可以不写循环,最终的列和都为1。
set.seed(1234)
data<-matrix(runif(20),4,5,byrow=TRUE,
dimnames=list(LETTERS[1:4],letters[1:5]))
data
#> a b c d e
#> A 0.1137034 0.622299405 0.6092747 0.6233794 0.8609154
#> B 0.6403106 0.009495756 0.2325505 0.6660838 0.5142511
#> C 0.6935913 0.544974836 0.2827336 0.9234335 0.2923158
#> D 0.8372956 0.286223285 0.2668208 0.1867228 0.2322259
#method 1 :
data1<-apply(data,1,`/`,colSums(data))
t(data1)
#> a b c d e
#> A 0.04976295 0.425360398 0.4378925 0.2597826 0.4531829
#> B 0.28023561 0.006490636 0.1671366 0.2775789 0.2707001
#> C 0.30355421 0.372506725 0.2032038 0.3848250 0.1538741
#> D 0.36644723 0.195642241 0.1917671 0.0778135 0.1222429
colSums(t(data1))
#> a b c d e
#> 1 1 1 1 1
#method 2 :
data2<-matrix(NA,4,5,
dimnames=list(LETTERS[1:4],letters[1:5]))
options(digits = 4)
for (i in 1:ncol(data)){
for (j in 1:nrow(data)){
data2[j,i]=data[j,i]/(colSums(data)[i])
}
}
data2
#> a b c d e
#> A 0.04976 0.425360 0.4379 0.25978 0.4532
#> B 0.28024 0.006491 0.1671 0.27758 0.2707
#> C 0.30355 0.372507 0.2032 0.38482 0.1539
#> D 0.36645 0.195642 0.1918 0.07781 0.1222
colSums(data2)
#> a b c d e
#> 1 1 1 1 1
#method 3 :
data3<-data/matrix(rep(colSums(data),each=4),4,5,byrow=F)
data3
#> a b c d e
#> A 0.04976 0.425360 0.4379 0.25978 0.4532
#> B 0.28024 0.006491 0.1671 0.27758 0.2707
#> C 0.30355 0.372507 0.2032 0.38482 0.1539
#> D 0.36645 0.195642 0.1918 0.07781 0.1222
colSums(data3)
#> a b c d e
#> 1 1 1 1 1
<sup>Created on 2020-07-23 by the reprex package (v0.3.0)</sup>