How can I add rows to an R data frame every other row?

前端 未结 5 1537
情书的邮戳
情书的邮戳 2020-12-19 07:49

Brief: how can I add m rows to my m X n data frame, where each new row is inserted after each existing row? I will essentially copy the existing ro

5条回答
  •  一整个雨季
    2020-12-19 08:29

    Here's one possible approach if I understand what you're doing:

    dat <- head(CO2, 10) # fake data set
    
    L1 <- lapply(1:nrow(dat), function(i) {
        dat2x <-  dat[i, ]
        dat2x[4] <- dat[i, 4] - dat[i, 5]
        rbind(dat[i, ], dat2x)
    })
    do.call(rbind, L1)
    

    EDIT: totally working off e4e5f4's excellent response:

    new <- dat[rep(1:nrow(dat),1,each=2),]
    new[c(F, T),4] <- dat[4] - dat[5]
    

    Both are equivalent but I assume the alter is way faster.

提交回复
热议问题