数据帧中的条件逐列或逐行减法

时间:2014-11-07 19:38:55

标签: r dataframe

我需要在R中进行逐列减法和逐行减法。

id    on    fail  
1   10-10-2014  11-11-2014  
1   11-10-2014  12-12-2014  
1   12-10-2014  12-01-2015  
2   13-10-2014  12-02-2015  
2   14-10-2014  15-03-2015  
2   15-10-2014  15-04-2015  
2   16-10-2014  16-05-2015  
3   17-10-2014  16-06-2015  
3   18-10-2014  17-07-2015  
3   19-10-2014  17-08-2015  
3   20-10-2014  17-09-2015 

例如,在上表中,每当出现新的id时,它应该进行逐列减法,否则它应该进行逐行减法。我需要得到这样的结果:

id      on        fail     res  
1   10-10-2014  11-11-2014  32  
1   11-10-2014  12-12-2014  31  
1   12-10-2014  12-01-2015  31  
2   13-10-2014  12-02-2015  122  
2   14-10-2014  15-03-2015  31  
2   15-10-2014  15-04-2015  31  
2   16-10-2014  16-05-2015  31  
3   17-10-2014  16-06-2015  242  
3   18-10-2014  17-07-2015  31  
3   19-10-2014  17-08-2015  31  
3   20-10-2014  17-09-2015  31 

截至目前,我正在使用以下代码:

data[,2] <- as.Date(data[,2],format="%d-%m-%Y")  
data[,3] <- as.Date(data[,3],format="%d-%m-%Y")  
x <- as.numeric(diff(data[,3]))

1 个答案:

答案 0 :(得分:0)

DF <- read.table(text="id    on    fail  
1   10-10-2014  11-11-2014  
1   11-10-2014  12-12-2014  
1   12-10-2014  12-01-2015  
2   13-10-2014  12-02-2015  
2   14-10-2014  15-03-2015  
2   15-10-2014  15-04-2015  
2   16-10-2014  16-05-2015  
3   17-10-2014  16-06-2015  
3   18-10-2014  17-07-2015  
3   19-10-2014  17-08-2015  
3   20-10-2014  17-09-2015 ", header=TRUE)

DF[,2:3] <- lapply(DF[,2:3], as.Date, format="%d-%m-%Y")

DF$res <- c(NA, diff(DF$fail))
DF[c(TRUE ,diff(DF$id)!=0), "res"] <- DF[c(TRUE ,diff(DF$id)!=0), "fail"] - 
                                       DF[c(TRUE ,diff(DF$id)!=0), "on"]
#    id         on       fail res
# 1   1 2014-10-10 2014-11-11  32
# 2   1 2014-10-11 2014-12-12  31
# 3   1 2014-10-12 2015-01-12  31
# 4   2 2014-10-13 2015-02-12 122
# 5   2 2014-10-14 2015-03-15  31
# 6   2 2014-10-15 2015-04-15  31
# 7   2 2014-10-16 2015-05-16  31
# 8   3 2014-10-17 2015-06-16 242
# 9   3 2014-10-18 2015-07-17  31
# 10  3 2014-10-19 2015-08-17  31
# 11  3 2014-10-20 2015-09-17  31