这里我有一个函数,我想要平衡运动中物体的停止次数。为了实现这一点,有一个位置列表(其中此函数名为Trip),持续时间是行程长度,但将用于进一步开发代码。
现在要知道整个行程中停车的次数我要做的就是每次行程都有不同的位置:
X,Y,Z
10,11,13
12,11,14
13,11,15, ....
** 20,11,35
20,11,35
20,11,35 ** 比较自己知道哪些是平等的。
在最后一个位置,当对象保持在同一位置时,我们可以得出结论已经停止。因此,为了知道停止,我们需要将每个位置与下一个位置进行比较。
我写这段代码:
StopsNumber <- function(Trip,Duration)
{
i=1
aux = Trip
while(i<length(Trip))
{
if(aux[i] == aux[i+1] && aux[i] == aux[i+2]){
Stop = aux[i]
NStops = Nstops+1
}
aux = [aux+1]
i=i+1
} # end
return (Stop,Nstops)
}
我认为我不知道如何创建事物清单。例如:在Stop = aux [i]上我不知道它是否正常运行。因为我想做停止是一个列表(或一个矢量,有辅助,(对象已经安静的那些位置)。如果有多个停止,这样做,最后一个将替换其余的。
愿有人帮助我吗?
谢谢
答案 0 :(得分:0)
您对动作,间隔和停留的定义不清楚。因此代码相当长,以避免误解。否则它可以煮一两行。首先是一些明确的定义
小贴士:尝试使用循环函数apply(),sapply(),lapply()和foreach()而不是for()和while()的低级函数。
#your data added some more positions
mixed.vector = c(
10,11,13,
12,11,14,
13,11,15,
20,11,35,
20,11,35, #this is a stop
20,11,35,
13,11,25,
10,20,30,
10,20,30) #this is a stop
#convert data to appropiate data structure.
#I suggest a matrix. List of vector would also do
#some tricks to convert (multiple ways to do this)
#mixed vector to matrix
xyz.matrix = matrix(mixed.vector,ncol=3,byrow=TRUE)
print(xyz.matrix) #each row is a position, columns are x, y and z respectively.
#matrix to list of vectors (if this structure is preferred)
list_of_vectors = split(xyz.matrix,1:dim(xyz.matrix)[1])
print(list_of_vectors)
#list of vectors to matrix (if this is how your data initially is ordered)
xyz.matrix = do.call(rbind,list_of_vectors)
print(xyz.matrix) #and we're back with a matrix
#function checking if intervals have no movement
#(total number of intervals is number of positions minus 1)
find_interval_with_movement = function(XYZ.m) {
nrows = dim(XYZ.m)[1] #scalar of n.position rows
interval_with_movement = !apply(XYZ.m[-nrows,]==XYZ.m[-1,],1,all) #check pairs of row if x y z match.
return(interval_with_movement)
}
#function finding stops, optional assuming the object was moving before first interval
find_stops = function(interval_movements,object.moving.at.t0=TRUE) {
intervals_to_search= c(object.moving.at.t0,interval_movements)
len = length(intervals_to_search)
#search for intervals with no movement where previous interval has movement
did.stop = sapply(2:len,function(i) all(intervals_to_search[(i-1):i] == c(T,F)))
return(did.stop)
}
#these intervals has no movement
print(!find_interval_with_movement(xyz.matrix))
#these intervals had no movement, where previous had
print(find_stops(find_interval_with_movement(xyz.matrix)))
#and the full number of stops
print(sum(find_stops(find_interval_with_movement(xyz.matrix))))