我正试图找出如何在data.frame
中的每一行之间添加一行。例如:
xdf <- data.frame(name = c(letters[1:5]),
w1 = runif(5, min = 1, max = 10),
w2 = runif(5, min = 10, max = 20))
name w1 w2
1 a 7.217998 14.51789
2 b 6.583311 13.01331
3 c 1.655201 18.83256
4 d 1.117273 19.81330
5 e 2.925724 13.21518
所以,我们假设我们的行只是第5行是e而我所说的是:
name w1 w2
1 a 7.217998 14.51789
e 2.925724 13.21518
2 b 6.583311 13.01331
e 2.925724 13.21518
3 c 1.655201 18.83256
e 2.925724 13.21518
4 d 1.117273 19.81330
e 2.925724 13.21518
5 e 2.925724 13.21518
提前致谢。
答案 0 :(得分:6)
我们可以rbind
具有最后一行(nrow
)的行序列,连接(c
),使用它来对数据集进行子集化,删除最后一行{{1并将行名称设置为NULL。
head
答案 1 :(得分:4)
您可以使用基础的apply
和rbind
组合:
do.call(rbind,apply(xdf, 1,function(x) rbind(x,xdf[5,])))
答案 2 :(得分:3)
你也可以使用矩阵索引来做同样的事情:
m <- matrix(NA, nrow = nrow(xdf)*2-1, ncol = ncol(xdf), dimnames = list(NULL, names(xdf)))
m[c(T,F),] <- as.matrix(xdf) # odd indices
m[c(F,T),] <- as.matrix(xdf[rep(5, nrow(xdf)-1),]) # even indices
data.frame(m)
# name w1 w2
# 1 a 7.217998 14.51789
# 2 e 2.925724 13.21518
# 3 b 6.583311 13.01331
# 4 e 2.925724 13.21518
# 5 c 1.655201 18.83256
# 6 e 2.925724 13.21518
# 7 d 1.117273 19.81330
# 8 e 2.925724 13.21518
# 9 e 2.925724 13.21518
<强>基准强>
library(microbenchmark)
set.seed(1)
xdf <- data.frame(name = c(letters[1:5]),
w1 = runif(5, min = 1, max = 10),
w2 = runif(5, min = 10, max = 20))
f_989 <- function(xdf){
m <- matrix("", nrow = nrow(xdf)*2-1, ncol = ncol(xdf),
dimnames = list(NULL, names(xdf)))
m[c(T,F),] <- as.matrix(xdf)
m[c(F,T),] <- as.matrix(xdf[rep(5, 4),])
data.frame(m)
}
f_akrun <- function(xdf) `row.names<-`(head(xdf[c(rbind(1:nrow(xdf),
nrow(xdf))),],-1), NULL)
f_jamieRowen <- function(xdf) do.call(rbind,apply(xdf, 1,function(x) rbind(x,xdf[5,])))
microbenchmark(f_akrun(xdf), f_989(xdf), f_jamieRowen(xdf))
# Unit: microseconds
# expr min lq mean median uq max neval
# f_akrun(xdf) 89.240 109.3715 118.7190 113.879 126.348 248.188 100
# f_989(xdf) 417.353 447.4000 495.6733 459.869 482.555 1521.879 100
# f_jamieRowen(xdf) 1216.902 1262.1230 1303.2455 1298.930 1332.883 1471.100 100