周期序列是在n项后重复自身的序列,例如以下是周期序列:
1, 2, 3, 1, 2, 3, 1, 2, 3, ...
我们将该序列的周期定义为每个子序列中的项数(上面的子序列是 1、2、3)。所以上述序列的周期是 3。
在 R 中,我可以定义上述序列(尽管不是无穷大),使用:
sequence <- rep(c(1,2,3),n) #n is a predefined variable
Run Code Online (Sandbox Code Playgroud)
因此,如果n = 50,sequence将是序列 1, 2, 3, 1, 2, 3, ... , 1, 2, 3,其中每个数字都以明显的方式出现了 50 次。
我正在寻找构建一个函数来计算sequence. 伪代码如下:
period <- function(sequence){
subsequence <- subsequence(sequence) #identify the subsequence
len.subsequence <- length(subsequence) #calculate its length
return(len.subsequence) #return it
}
Run Code Online (Sandbox Code Playgroud)
我将如何识别子序列?这有点像rep函数的反转,这样我传入一个序列并传出初始向量的长度。
在RI中具有以下内容matrix(每行代表从相同样本数据生成的自举95%置信区间):
low high
[1,] 22.2 25.5
[2,] 23.1 25.9
[3,] 23.4 26.1
...
Run Code Online (Sandbox Code Playgroud)
我知道数据的真实总体平均值,它是23.3.所以前两个包括真正的意思,但第三个没有.
在R中,我想运行一个for循环i遍历nrow(matrix)时间,每个都i检查数据的真实总体均值是否在该特定区间内,然后如果区间包含真实均值则返回高度nrow(matrix)的列向量TRUE,FALSE否则.
我怎么能这样做?
我正在寻找运行这个for循环,但执行需要一个不可接受的长时间(~20s).x和y是长度为2000000的预定义矢量.
for(i in 1:2000000)
{
a <- runif(1)
b <- runif(1)
sqrtf <- sqrt(-log(b,10))
x[i] <- sqrtf*cos(a)
y[i] <- sqrtf*cos(b)
}
Run Code Online (Sandbox Code Playgroud)
有什么技巧可以加快这一点吗?
编辑:修复了sqrtf
我有以下(无意义)功能,在R:
say <- function (string){
if(!exists("string")){
stop("no output string was specified")
}
cat(string)
}
Run Code Online (Sandbox Code Playgroud)
在检查字符串对象实际存在时,这一切都很好.但是,如果同名的对象已经在工作空间中浮动,它将忽略该错误,即使该函数中未定义该错误.
我可以这样做,所以exists()函数只能在对象的函数空间中查找吗?
在RI中有以下示例模块,它重复一个for循环n时间:
function(n){
#inputs - n - number of results required
#reserve n spaces for results
r_num_successes <- 1:n
#start looping n times
for(i in 1:n){
#set first uniform "random" deviate equal to 0.05 and number of successes to 0
current_unif <- 0.05
num_successes <- 0
#start while loop that updates current_unif - it runs as long as
#current_unif is less than 0.95, increments num_successes each loop
while(current_unif < 0.95){
#set current_unif to a uniform random deviate between the …Run Code Online (Sandbox Code Playgroud)