我有这些数据:
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
请问如何用星号插入这些行?
谢谢。
答案 0 :(得分: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
答案 1 :(得分: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