1

我有这个数据:

hhid    perid actNo thisAct from   to tripTime  
8019450     1     1    home  180 1051       NA  
8019450     1     2  school 1075 1245       24  
8019450     1     3  socrec 1255 1260       10  
8019450     1     4    home 1280 1619       20

现在,我想在其中插入三行

thisAct=travel
from=(from-tripTime-1)
to=(from-1)

然后,预期的数据如下所示:

hhid    perid actNo thisAct from   to tripTime  
8019450     1     1    home  180 1051       NA  
*8019450    1     2  travel 1052 1074         
8019450     1     3  school 1075 1245       24  
*8019450    1     4  travel 1246 1254         
8019450     1     5  socrec 1255 1260       10  
*8019450    1     6  travel 1261 1279         
8019450     1     7    home 1280 1619       20  

请问如何用星号插入这些行?

谢谢你。

4

2 回答 2

3

首先重新创建数据:

dat <- read.table(text="
                  hhid    perid actNo thisAct from   to tripTime  
c     1     1    home  180 1051       NA  
8019450     1     2  school 1075 1245       24  
8019450     1     3  socrec 1255 1260       10  
8019450     1     4    home 1280 1619       20
                  ", header=TRUE)

现在计算旅行时间并将其放入与您的数据形状相同的数据框中

travel <- data.frame(
  hhid = 8019450,
  perid = 1,
  actNo = NA,
  thisAct = "travel",
  from = head(dat$to + 1, -1),
  to   = tail(dat$from - 1, -1),
  tripTime = NA
)

然后rbind排序:

x <- rbind(dat, travel)
x <- x[order(x$from), ]
x$perid <- seq_along(x$perid)
x

     hhid perid actNo thisAct from   to tripTime
1       c     1     1    home  180 1051       NA
5 8019450     2    NA  travel 1052 1074       NA
2 8019450     3     2  school 1075 1245       24
6 8019450     4    NA  travel 1246 1254       NA
3 8019450     5     3  socrec 1255 1260       10
7 8019450     6    NA  travel 1261 1279       NA
4 8019450     7     4    home 1280 1619       20
于 2012-10-24T08:11:01.097 回答
1

您的数据:

dat <- read.table(text="hhid perid actNo thisAct from to tripTime
8019450 1 1 home 180 1051 NA
8019450 1 2 school 1075 1245 24
8019450 1 3 socrec 1255 1260 10
8019450 1 4 home 1280 1619 20", header = TRUE, stringsAsFactors = FALSE)

这是一种获得你想要的东西的方法:

dat2<- dat[c(1, rep(2:nrow(dat), each = 2)), ]
dat2$actNo <- 1:nrow(dat2)
dat2[c(FALSE, TRUE), "thisAct"] <- "travel"
dat2[c(FALSE, TRUE), "to"] <- dat2[c(FALSE, TRUE), "from"] - 1
dat2[c(FALSE, TRUE), "from"] <- (dat2[c(FALSE, TRUE), "from"] -
                                 dat2[c(FALSE, TRUE), "tripTime"]) + 1    
dat2[c(FALSE, TRUE), "tripTime"] <- NA

由于tripTime未指定列内的值,因此我选择NA了新列。

输出:

#        hhid perid actNo thisAct from   to tripTime
# 1   8019450     1     1    home  180 1051       NA
# 2   8019450     1     2  travel 1052 1074       NA
# 2.1 8019450     1     3  school 1075 1245       24
# 3   8019450     1     4  travel 1246 1254       NA
# 3.1 8019450     1     5  socrec 1255 1260       10
# 4   8019450     1     6  travel 1261 1279       NA
# 4.1 8019450     1     7    home 1280 1619       20
于 2012-10-24T08:10:10.537 回答