我在编程方面很陌生,我从R开始。我想制作一个脚本,它将带有列的矩阵作为输入:time,x,y(coordenates)然后划分每个象限花费的时间一个圆形区域。我有一个大致完成的脚本,但由于任何原因我不明白,当我在编辑器中执行for循环时,它在控制台中显示所有字母为红色,每行的开头都有一个“+”,这不是当我打电话时,让我再打开任何其他物体。
set.seed(20)
x = matrix(rnorm(10,3,4),10,1)
y = matrix (rnorm(10,3,4),10,1)
time = matrix (1:10,10,1)
a = cbind (time,x,y)
colnames(a) = c("time","x","y")
upperright = a[,2] > 0 && a[,3] > 0
upperleft = a[,2] < 0 && a[,3] > 0
lowerright = a[,2] > 0 && a[,3] < 0
lowerleft = a[,2] < 0 && a[,3] < 0
calculation <- function () {
upperrightquadrant = 0
upperleftquadrant = 0
lowerrightquadrant = 0
lowerleftquadrant = 0
for (i in c(1:nrow(a))){
if (upperright) upperrightquadrant <<- sum((a[i,1]-a[i-1,1]))
if (upperleft)upperleftquadrant <<- sum((a[i,1]-a[i-1,1]))
if (lowerright) lowerrightquadrant <<-sum((a[i,1]-a[i-1,1]))
if (lowerleft) lowerleftquadrant <<- sum((a[i,1]-a[i-1,1]))
}}
output = lapply (a, calculation)
答案 0 :(得分:2)
+
符号只是表示当前语句是否包含前一行语句的方法。那完全没问题。您的程序还有一些其他问题阻止它产生您的预期结果。事实上,如果我理解你想要做什么,我最后添加了一个可能的解决方案。首先,让我建议编辑及其原因:
&
代替&&
。 &
是向量化运算符。因此,upperright = a[,2] > 0 & a[,3] > 0
代替upperright = a[,2] > 0 && a[,3] > 0
。calculation <- function (a)
而不是calculation <- function ()
。if (upperright[i])
而不是if (upperright)
。sum((a[i,1]-a[i-1,1]))
在i == 1,i-1等于0.如果你只计算,将计数递增1就足够了。<<-
。最后,因为您已经编写了for
循环来迭代遍历矩阵,所以不需要lapply或其他类似的循环函数。
仅提供建议:使用<-
运算符代替=
进行分配。
现在,纠正的程序:
set.seed(20)
x = matrix(rnorm(10,3,4),10,1)
y = matrix (rnorm(10,3,4),10,1)
time = matrix (1:10,10,1)
a = cbind (time,x,y)
colnames(a) = c("time","x","y")
upperright = a[,2] > 0 & a[,3] > 0
upperleft = a[,2] < 0 & a[,3] > 0
lowerright = a[,2] > 0 & a[,3] < 0
lowerleft = a[,2] < 0 & a[,3] < 0
calculation <- function (a) {
upperrightquadrant = 0
upperleftquadrant = 0
lowerrightquadrant = 0
lowerleftquadrant = 0
for (i in c(1:nrow(a))){
if (upperright[i]) upperrightquadrant <- upperrightquadrant + 1
if (upperleft[i]) upperleftquadrant <- upperleftquadrant + 1
if (lowerright[i]) lowerrightquadrant <- lowerrightquadrant + 1
if (lowerleft[i]) lowerleftquadrant <- lowerleftquadrant + 1
}
list(upperrightquadrant = upperrightquadrant, upperleftquadrant = upperleftquadrant,
lowerrightquadrant = lowerrightquadrant, lowerleftquadrant = lowerleftquadrant)
}
output = calculation(a)
print(a) # input
print(output) # output
这是您所请求的内容的编辑(时间实例不连续的情况)。只需用这一个替换for
循环:
for (i in c(1:nrow(a))){
if(i>1){
if (upperright[i]) upperrightquadrant <- upperrightquadrant + a[i, 1] - a[i-1, 1]
if (upperleft[i]) upperleftquadrant <- upperleftquadrant + a[i, 1] - a[i-1, 1]
if (lowerright[i]) lowerrightquadrant <- lowerrightquadrant + a[i, 1] - a[i-1, 1]
if (lowerleft[i]) lowerleftquadrant <- lowerleftquadrant + a[i, 1] - a[i-1, 1]
} else {
if (upperright[i]) upperrightquadrant <- upperrightquadrant + a[i, 1]
if (upperleft[i]) upperleftquadrant <- upperleftquadrant + a[i, 1]
if (lowerright[i]) lowerrightquadrant <- lowerrightquadrant + a[i, 1]
if (lowerleft[i]) lowerleftquadrant <- lowerleftquadrant + a[i, 1]
}
}
希望,这有帮助。