[程式] R 如何產出table 不透過迴圈?已刪文
[軟體程式類別]:R
[程式問題]:
各位好,
我是R新手, 透過R寫了一個函式, output是數字,
想根據不同的參數, 將結果print在一個table(比如5*5 table),但不用迴圈做.
我自己有試過apply(), 試不出來, 請問還有甚麼其他funtion可以用嗎?
下面的函式 其中d,s是生女兒跟生男生個數(介於0-5),p是生男孩機率.
ex: f_size(3,2,0.5)=6.875
然後 我想把結果印成6*6的table, 有不用迴圈的方法嗎?
我嘗試用如下方式試寫 但一直出現error message:
Error in FUN(newX[, i], ...) : unused argument(s) (newX[, i])
是哪寫錯了呢?有其他不用迴圈的方法嗎?
謝謝!
x <- cbind(x1 = 0, x2 = c(0:5))
myFUN <- function(x, c1, c2) {
d <- c1
s <- c2
p <- 0.5
f_size(d,s,0.5)
}
apply(x,1,myFUN,c1='x1',c2='x2')
[函式程式]:
f_size <- function(d,s,p){
if (d==0 & s==0) {
f_size = 0
print(f_size)
}
else {
q <- 1-p;
a <- matrix(0,6,6);
a[1,1] <- 0; # S=0, d=0
for (ss in c(1:5)){
a[ss+1,1]=ss/p
}
for (dd in c(1:5)){
a[1,dd+1]=dd/q
}
for (dd in c(1:5)){
for (ss in c(1:5)){
# print(ss)
a[ss+1,dd+1]=1+p*a[ss,dd+1]+q*a[ss+1,dd]
}
}
print(a[s+1,d+1])
}
}
※ 編輯: wgene (100.36.131.156 美國), 02/11/2021 00:09:37
→
02/11 00:10,
5年前
, 1F
02/11 00:10, 1F
→
02/11 00:21,
5年前
, 2F
02/11 00:21, 2F
※ 編輯: wgene (100.36.131.156 美國), 02/11/2021 00:25:36
※ 編輯: wgene (100.36.131.156 美國), 02/11/2021 00:26:38
※ 編輯: wgene (100.36.131.156 美國), 02/11/2021 00:27:28
※ 編輯: wgene (100.36.131.156 美國), 02/11/2021 00:30:00