How to cut a vector or column into intervals in R [duplicate]

放肆的年华 提交于 2021-02-05 11:46:39

问题


I have the following columns in a dataframe which difference between each row is 0.012 s :

Time
 0
 0.012
 0.024
 0.036
 0.048
 0.060
 0.072
 0.084
 0.096
 0.108

I want to come up with intervals starting from beginning increasing by 0.030, so intervals or time window of every 0.03 later to be used in group by.


回答1:


You can try findInterval like

findInterval(df$Time, seq(min(df$Time), max(df$Time), 0.03))
#[1] 1 1 1 2 2 3 3 3 4 4

We can also use cut

breaks <- seq(min(df$Time), max(df$Time), 0.03)
cut(df$Time, c(breaks, Inf), labels = breaks, include.lowest = TRUE)
#[1] 0    0    0    0.03 0.03 0.03 0.06 0.06 0.09 0.09

data

df <- structure(list(Time = c(0, 0.012, 0.024, 0.036, 0.048, 0.06, 
0.072, 0.084, 0.096, 0.108)), class = "data.frame", row.names = c(NA, -10L))


来源:https://stackoverflow.com/questions/57905792/how-to-cut-a-vector-or-column-into-intervals-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!