2017-03-10 87 views
1

我有一个很大的数据框,有p列和n行。
我想更改ID,即如果获得值1,则拆分帧。但是,对于每个ID,该值可能会出现多次,因此变得棘手。
我正在考虑订购,因此每次使用df $ Value == 1时,该行应该有df $ order == 1(next,2 ... until a df $ value == 1 again)根据值拆分ID

# Example data 
df <- data.frame(ID= c(rep(1,3), rep(2,7), rep(3,5)), 
      Value= c(0,0,1, 
         0,0,1,0,1,1,0, 
         0,0,1,0,1)) 

# Desired result 
df <- data.frame(ID= c(rep(1,3), rep(2,3), rep(2.1,2), rep(2.2,1),rep(2.3,1), rep(3,3), rep(3.1,2)), 
      Value= c(0,0,1, 
         0,0,1, 
         0,1, 
         1, 
         0, 
         0,0,1, 
         0,1)) 

# Alternative desired result 
df <- data.frame(ID= c(rep(2,3), rep(2.1,2), rep(2.2,1),rep(2.3,1), rep(3,3), rep(3.1,2)), 
      Value= c(0,0,1, 
         0,1, 
         1, 
         0, 
         0,0,1, 
         0,1)) 

我试图做到这一点:

df %>% group_by(ID) %>% mutate(Order= seq(from=Value[1], to=which(Value==1), by=1)) 

但它不真的给我我想要的。
有什么建议吗?

回答

2

下面是使用data.table

library(data.table) 
setDT(df)[, ID := seq(0, 1, by = 0.1)[shift(cumsum(Value==1), fill=0)+1] + ID, ID] 

或者同与dplyr

library(dplyr) 
df %>% 
    group_by(ID) %>% 
    mutate(ID1 = seq(0, 1, by = 0.1)[lag(cumsum(Value==1), default=0)+1] + ID) %>% 
    ungroup() %>% 
    mutate(ID = ID1) %>% 
    select(-ID1) 
# A tibble: 15 × 2 
#  ID Value 
# <dbl> <dbl> 
#1 1.0  0 
#2 1.0  0 
#3 1.0  1 
#4 2.0  0 
#5 2.0  0 
#6 2.0  1 
#7 2.1  0 
#8 2.1  1 
#9 2.2  1 
#10 2.3  0 
#11 3.0  0 
#12 3.0  0 
#13 3.0  1 
#14 3.1  0 
#15 3.1  1 
+1

我不是在data.table非常有信心的一个选项。但我理解dplyr解决方案,非常聪明的做法。谢谢! – TKN