简体   繁体   English

R:尝试用特定条件填充一列

[英]R: Try to fill in a column with values by certain condition

i really need advice for following task in R: I have a column with time and one with intervals.我真的需要在 R 中完成以下任务的建议:我有一个带有时间的列和一个带有间隔的列。 For later aggregation I have to set intervals for the time.对于以后的聚合,我必须设置时间间隔。 Example: I have the table:示例:我有一张桌子:

time   interval

1        NA
2        NA
3        NA
4        NA
5        NA
6        NA

Expecting:期待:

time   interval
1          5
2          5
3          5
4          5
5          5
6         10  
14        15

Code:代码:

count=0
dt = 5
dt_temp = 5

for (i in df_start$time){

if (i<dt) {
df_start$interval[count] =dt

}else{
dt= dt+dt_temp
df_start$interval[count] =dt
}
count = count+1
}

Outcome(or check picture):结果(或检查图片):

time    interval
1           5
2           5
3           5
4           5
4.946      10  (wrong)
5.021      15  (totally wrong)
6.023      20  (totally wrong)

I am really going nuts, since I sit nearly half a day to find the problem.我真的要疯了,因为我坐了将近半天才发现问题。 Thanks in advance!提前致谢!

Image of my solution我的解决方案的图像

Here is a base R solution, where ceiling is used:这是一个基本的 R 解决方案,其中使用了ceiling

df$interval <- ceiling(df$time/5)*5

such that以至于

> df
  time interval
1    1        5
2    2        5
3    3        5
4    4        5
5    5        5
6    6       10
7   14       15

DATA数据

df <- structure(list(time = c(1L, 2L, 3L, 4L, 5L, 6L, 14L)), row.names = c(NA, 
-7L), class = "data.frame")

df_start$interval = ((df_start$time - 1) %/% 5 + 1) *5

Try this code:试试这个代码:

df_start <- data.frame(time = c(1,2,3,4,5,6,14), interval = 0)

count= 1

dt = 5

dt_temp = 5

for (i in df_start$time){

if (i<=dt) {
df_start$interval[count] =dt

}else{
dt= dt+dt_temp
df_start$interval[count] =dt
}
count = count+1
}

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

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