R 如何插入多行
我有以下数据:R 如何插入多行,r,R,我有以下数据: 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
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
你能告诉我如何插入那些带星号的行吗
谢谢。您的数据:
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)
您的数据:
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)
从重新创建数据开始:
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)
从重新创建数据开始:
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)
您需要如何插入数据,是有一个通用模式,还是只需要在现有的4行中插入这3行?是的,有一个通用模式。谢谢。您需要如何插入数据有一个通用模式,还是只需要在现有的4行中插入这3行?是的,有一个通用模式。谢谢
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
)
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