与data.frame中的交替行组进行比较时的计数频率
我有一张我想坐的桌子与data.frame中的交替行组进行比较时的计数频率,r,loops,count,frequency,R,Loops,Count,Frequency,我有一张我想坐的桌子 每四行分组为连续的组 将每一行与上一组中的4行进行比较 实际上,我将一次使用四行作为参考集,其中将比较以下四组中的每一行 具体来说,给定组x中的一行,我想计算前一组(即组x-1)中有多少行的值小于或等于感兴趣行中的值 我想为每一行这样做 因此,我想计算第二组四行中的每一行(比如5到8行),第一组(比如1到4行)中值小于或等于它的行数。然后,第5行到第8行成为接下来四行(9到12)的下一个参考组。等等 结果如下: Row Values Count 1 1.35
- 每四行分组为连续的组
- 将每一行与上一组中的4行进行比较
Row Values Count
1 1.35
2 0.71
3 1.00
4 0.07
5 0.53 1
6 0.12 1
7 0.36 1
8 2.03 4
9 3.83 4
10 1.30 3
11 2.17 4
12 1.71 3
13 1.52 1
14 1.27 0
15 0.29 0
16 0.05 0
17 0.14 1
您可以尝试(如果df
是您的data.frame):
sdf您可以尝试以下方法:
dat<-data.frame(row=c(1:length(z)),Values=z,ceiling=c(rep(NA,length(z))),count=c(rep(NA,length(z))))
#where z is a vector of your values.
for(x in 1:dim(dat)[1]) {
dat$ceiling[x]<-ceiling(x/4)
dat$count[x]<-length(which(dat$Values[dat$ceiling == (dat$ceiling[x]-1)] <= dat$Values[x]))
}
dat将天花
功能与lappy
或vapply
一起使用
天花
接受单个数值参数x
,并返回一个数值向量,该向量包含不小于x
- 要达到所需效果,请将x除以每个组中所需的行数
ceiling(x/y) #where x = the row number and y = the number of rows per group
(假设df
是您的数据帧):
使用lappy
:
z <- df$Values
Groups <- ceiling(seq(z)/4)
df$Count <-
unlist(lapply(seq(z), function(x) sum(z[x] >= z[Groups == Groups[x] - 1])))
df$Count <-
vapply(seq(z), function(x) sum(z[x] >= z[Groups == Groups[x] - 1]), integer(1))
如果需要单个命令:
df$Count <-
with(df,unlist(lapply(seq(Values), function(x)
sum(Values[x] >= Values[ceiling(seq(Values)/4) == ceiling(seq(Values)/4)[x] - 1]))))
df$Count=Values[上限(seq(Values)/4)=上限(seq(Values)/4)[x]-1]))
这当然是假设您的行从1开始,按顺序增加1。谢谢@nicola。这正是我想要的。很高兴它起了作用。如果你觉得答案有用,请考虑接受我的回答。
df$Count <-
vapply(seq(z), function(x) sum(z[x] >= z[Groups == Groups[x] - 1]), integer(1))
df$Count <-
with(df,unlist(lapply(seq(Values), function(x)
sum(Values[x] >= Values[ceiling(seq(Values)/4) == ceiling(seq(Values)/4)[x] - 1]))))