gpt4 book ai didi

r - 在 R 中使用 rbind.fill 时保留行名称

转载 作者:行者123 更新时间:2023-12-01 22:38:22 25 4
gpt4 key购买 nike

有谁知道如何在rbind.fill函数中保留行名。

library(plyr)

#creating data
a <- mtcars[ 1:5 , c("mpg","hp","gear") ]
b <- mtcars[ 6:10 , c("mpg","disp","gear") ]

#does not work because there are different colnames
rbind(a,b)

#works but eliminates the rownames
bound <- rbind.fill( a , b )

我正在设置一个循环,其中对象将使用 rbind.fill 连接。现在我正在使用这样的组合函数:

namess <- c( rownames(a) , rownames(b) )
rownames(bound) <- namess

我想可能有更好的方法。谢谢!

最佳答案

您可以尝试应用一个自定义函数来执行rbind.fill并自动设置初始行名,如下所示:

# List of sample data
ab.list <- list(a <- mtcars[1:5 , c("mpg","hp","gear")],
b <- mtcars[6:10 , c("mpg","disp","gear")])

# Apply custom function (rbind and rownames adjustment) to sample data
do.call(function(...) {

tmp <- plyr::rbind.fill(...)
rownames(tmp) <- sapply(ab.list, function(i) {
rownames(i)
})

return(tmp)

}, ab.list)

mpg hp gear disp
Mazda RX4 21.0 110 4 NA
Mazda RX4 Wag 21.0 110 4 NA
Datsun 710 22.8 93 4 NA
Hornet 4 Drive 21.4 110 3 NA
Hornet Sportabout 18.7 175 3 NA
Valiant 18.1 NA 3 225.0
Duster 360 14.3 NA 3 360.0
Merc 240D 24.4 NA 4 146.7
Merc 230 22.8 NA 4 140.8
Merc 280 19.2 NA 4 167.6

查看this previous post处理类似的问题。

关于r - 在 R 中使用 rbind.fill 时保留行名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16422176/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com