我需要为袋熊的运动编写一个函数,这个函数相对于它们的起始点和它们喜欢的洞穴范围(在起始的洞穴周围大约有3-8个洞)。
要做到这一点,我需要:
- If odd, no problem (e.g. 24 and 5 burrows -> 22, 23, 24, 25, 26)
- If even, do the same as odd and then add another number to the left or right (e.g. 24 and 4 burrows -> 22, 23, 24, 25)
我应该如何合乎逻辑地处理这个问题呢?
因此,洞穴排列的方式是,它们被排列成一个圆形的图案(它们的栖息地的边缘)。我以为我可以做%函数来创建一个模块化函数,但是我不知道如何做数字4和5,以及如何将所有东西都变成一个函数。
到目前为止,我想出了第三步.
burrownum = (1:246) #set number of burrows
rand_burrownum = permute::shuffle(burrownum) #randomise the burrows
assignbur2wom = as.data.frame(rand_burrownum[1:24]) #assign wombats (per set proportion - 24 for 10%, 43 for 17.5%, 61 for 25%) to initial burrow
wombatID = as.data.frame(1:24) #ID of each wombats - need to change the number of individuals
assignpref2wom = as.data.frame(sample(3:8, 24, replace = TRUE))#sample how many of burrows each wombat prefers - need to change number of individuals
wombatdat$WomID = wombatID
wombatdat$InitialBurrows = assignbur2wom
wombatdat$NumBPref = assignpref2wom我想得到一个创建这些条件的函数。我知道这很复杂,如果还有什么我可以澄清的,请告诉我!
发布于 2019-08-08 13:34:29
以下功能可能会有所帮助:
assign.burrows <- function(i,k,n = 246) {
a <- floor(i - 1 - (k-1)/2)
b <- floor(i - 1 + (k-1)/2)
1 + (a:b) %% n
}典型运行:
> assign.burrows(24,5)
[1] 22 23 24 25 26
> assign.burrows(24,4)
[1] 22 23 24 25
> assign.burrows(246,4)
[1] 244 245 246 1
> assign.burrows(246,5)
[1] 244 245 246 1 2
> assign.burrows(2,5)
[1] 246 1 2 3 4注意,使用基于1的钻孔数字索引会使事情变得更加复杂,因为它不能很好地处理模块化算法。对于基于0的索引(以便洞穴编号从0到245),您只需使用:
assign.burrows <- function(i,k,n = 246) {
a <- floor(i - (k-1)/2)
b <- floor(i + (k-1)/2)
(a:b) %% n
} 另一方面,基于1的索引在R数据结构中发挥得更好,因此总的来说,坚持R的基于1的索引可能更好。
https://stackoverflow.com/questions/57411703
复制相似问题