![](/img/trans.png)
[英]In R, with a list of matrices, how can I quickly find the difference between the first and second row in each matrix in the list?
[英]How can i add a row between each row in R?
我試圖找出如何在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
提前致謝。
我們可以rbind
與最后一排(行的序列nrow
),串聯( c
),用它來子集的數據集,用去掉最后一排head
,並設置行的名稱為NULL。
`row.names<-`(head(xdf[c(rbind(1:nrow(xdf), nrow(xdf))),],-1), NULL)
# 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
你可以使用apply
和基礎的rbind
的組合:
do.call(rbind,apply(xdf, 1,function(x) rbind(x,xdf[5,])))
你也可以使用矩陣索引來做同樣的事情:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.