我正在構建代碼以運行和管理可在三個站點羣組之一中的站點進行抽樣事件的模擬。我用rep()
分配隊列標識符(1,2或3)使用下面的代碼:爲什麼rep()的行爲與這個簡單的R例子不一致?
cohort <- rep(1:n.cohorts, n.sites)
我都首先把重點線,但重現我的問題,你需要運行下面的線,分配隊列之間的站點總數以便向rep()
呼叫呈現。
n.cohorts <- 3
s <- 10 # total available sites in this example
# different proportions of the total can be allocated to each cohort, for example
prop.control <- 0.4 ; prop.int <- 0.4 ; prop.ref <- 1-(prop.int+prop.control)
n.control <- prop.control * s; n.int <- prop.int * s; n.ref <- prop.ref * s
n.sites <- c(n.control, n.int, n.ref)
現在,n.sites
自行返回
[1] 4 4 2
所以當我再次運行我cohort <- rep(1:n.cohorts, n.sites)
呼叫我希望cohort
,爲10項的列表,像這樣:[1] 1 1 1 1 2 2 2 2 3 3
。我得到,然而,這只是9:
> cohort
[1] 1 1 1 1 2 2 2 2 3
如果我在何處運行n.sites
直接定義,像這樣同一代碼:n.sites <- c(4, 4, 2)
,我得到了10個項目我期待。我已經多次重做以說服自己,在兩種情況下,n.sites
本身都會產生相同的結果。
任何人都可以解釋爲什麼會發生這種情況?提前謝謝了。
大衛
我說你已經釘它。很高興我問。確認你的建議後,我運行'print(prop.ref,dig = 20)',答案是'0.19999999999999995559'! – dhd
這不是一個錯誤。這是有據可查的行爲。 'rep'需要一個'integer'參數,你提供一個'numeric'。 'numeric'到'integer'的轉換將總是截斷小數部分直到機器的精度。試試'as.integer(1.99999999999999); 1.99999999999999'。看到兩個結果。 –
對不起@ SimonO'Hanlon;你當然記得它是有據可查的,我的意思是將SEEM資本化而不是嚴重。但是對於很多人來說,分配問題是非常不直觀的,即'prop.control < - 0.4; print(prop.int,dig = 20); #[1] 0.4000000000000000222'這是更多的數字/數字問題,不是? – Troy