- 問題: 用for迴圈算z-score遇到的問題
[問題類型]
程式諮詢
[軟體熟悉度]:
新手(沒寫過程式,R 是我的第一次)
[問題敘述]:
不好意思小妹初學R又來打擾
想要把分數依照每位受試者去算z score
每位受試者有8個觀察值
於是我先分別計算平均數和標準差,如下
A20是我要標準化的變項,sub是受試者編號
wtpmean=aggregate(dat$A20,by=list(dat$sub),mean)
colnames(wtpmean)=c("sub","mean")
wtpsd=aggregate(dat$A20,by=list(dat$sub),sd)
colnames(wtpsd)=c("sub","sd")
接著我想要用迴圈來把分數標準化
zscore=0
for(i in 1:length(dat$A20)){
zscore=(subset(dat$A20,dat$sub==i)-wtpmean$mean[i])/wtpsd$sd[i]}
但是這裡就出現問題了,我的zscore是空的,我不知道是哪裡寫錯了
還是迴圈的用法不對呢?
[環境敘述]:
R version 3.3.0 (2016-05-03)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)
locale:
[1] LC_COLLATE=Chinese (Traditional)_Taiwan.950
[2] LC_CTYPE=Chinese (Traditional)_Taiwan.950
[3] LC_MONETARY=Chinese (Traditional)_Taiwan.950
[4] LC_NUMERIC=C
[5] LC_TIME=Chinese (Traditional)_Taiwan.950
attached base packages:
[1] stats graphics grDevices utils datasets methods
[7] base
loaded via a namespace (and not attached):
[1] tools_3.3.0