将数据帧中的行相应地移动到一列(2) [英] Move rows in a dataframe accordingly to one column (2)
问题描述
我需要调整@bgoldst建议的代码(谢谢)我的几个数据框,其中有一个日期窗口 计数列中的值最多为10天。
I need to adjust the code that @bgoldst suggested (thanks) to my several dataframes, which have a 'Day window' up to 10 days prior the days with values > 0 in the Count column.
这里是3天窗口数据框的示例:
Here an example of a '3 Day window' dataframe:
df <- read.table(text = 'ID Day Count
33012 9526 4
35004 9526 4
37006 9526 4
37008 9526 4
21009 1913 3
24005 1913 3
25009 1913 3
25009 14329 1
48007 9525 0
88662 9524 0
1845 9524 0
49002 1912 0
1664 1911 0', header = TRUE)
正如你所看到的,我有9526-9525-9524天(3天窗口) ,1913-1912-1911(3天窗口)。
As you can see I have got day 9526-9525-9524 (3 day window), 1913-1912-1911 (3 day window).
我需要在Count列(9525年,9524年,1912年,1911年)中移动0行相对次日,值> 0。
I need to move the rows with 0s in the Count column (day 9525, 9524, 1912, 1911) after the relative following day with values > 0.
这里我想要的输出:
ID Day Count
33012 9526 4
35004 9526 4
37006 9526 4
37008 9526 4
48007 9525 0
88662 9524 0
1845 9524 0
21009 1913 3
24005 1913 3
25009 1913 3
49002 1912 0
1664 1911 0
25009 14329 1
@bgoldst提供的代码对2天窗口(即9526-9525,1913-1912),但留下了第三天(9524和1911)。
The code that @bgoldst provided works good for a '2 day window' (i.e. 9526-9525, 1913-1912) but left behind the 3rd day (9524 and 1911).
代码是:
df[order(match(df$Day+(z <- df$Count==0L),unique(df$Day[!z])),z),];
我需要使用不同的时间窗口对我的几个数据框进行调整。
I need to adjust it for my several dataframes with different time windows.
推荐答案
data.table的一个选项
library(data.table)
dt <- setDT(df)[order(-Day, -Count)]
i1 <- dt[, if(uniqueN(Day)==3) .I, cumsum(c(TRUE, abs(diff(Day)) > 1))]$V1
i2 <- setdiff(seq_len(nrow(dt)), i1)
dt[c(i1,i2)]
# ID Day Count
# 1: 33012 9526 4
# 2: 35004 9526 4
# 3: 37006 9526 4
# 4: 37008 9526 4
# 5: 48007 9525 0
# 6: 88662 9524 0
# 7: 1845 9524 0
# 8: 21009 1913 3
# 9: 24005 1913 3
#10: 25009 1913 3
#11: 49002 1912 0
#12: 1664 1911 0
#13: 25009 14329 1
这篇关于将数据帧中的行相应地移动到一列(2)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!