繁体   English   中英

计算数组中值的更改次数

[英]count the number of changes of value in an array

我在R中相对较新,正在使用动物的行为数据,并且我试图确定在给定的时间范围内(本例中为会话)单个动物改变其行为的次数。

我的虚拟数据集为:-

session = c(1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2)
activity = c("V","F","D","F","F","W","V","R","R","S","V","U","W","V","V","V","R","R","R","R")
df = data.frame(session,activity)

我想计算活动在每个会话中更改的次数。 例如,在会话1中,它将是8倍,在会话2中,它将是5倍。 我尝试过遵循Internet上其他建议使用rle()选项,但我想知道如何编码,因为在大多数情况下,它将总结给定数组中的不同模式。

我从一个朋友那里发现我必须对我df的“活动”列使用权限,请确保此列是字符,而不是向量df$activity=as.character(df$activity) ,然后应用该功能仅适用于单个会话的行,例如会话1的行:

res<-rle(df[which(df$session==1),2])#rle() function applied to the activity column of df and to the rows of the session 1
length(res$lengths)# will give you the number of changes within a session

但要将其应用于大数据集,我可以将其循环应用:

df[,2]=as.character(df[,2])# to treat session as a character
ls.session=unique(df$session)
nb.session=length(ls.session)
new.df=data.frame(ls.session,rep(0,nb.session))#create an empty data.frame where we can apply the loop
names(new.df)=c("session","nb.change")
for(i in 1:nb.session){
res.rle.sess.i=rle(df[which(df$session==ls.session[i]),2])
nb.chang.sess.i=length(res.rle.sess.i$lengths)
new.df[i,2]=nb.chang.sess.i
}
new.df
change.f = function(x) c(FALSE, x[-1] != x[-length(x)])
aggregate(change.f(df$activity)&!change.f(df$session), by=list(df$session), FUN=sum)

输出:

  Group.1 x
1       1 7
2       2 4

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM