gpt4 book ai didi

r - 如何使用 dplyr 熔化和类型转换数据框?

转载 作者:行者123 更新时间:2023-12-02 08:29:44 25 4
gpt4 key购买 nike

最近我正在使用 dplyr 进行所有数据操作,它是一个出色的工具。但是我无法使用 dplyr 熔化或类型转换数据框。有什么办法可以做到这一点吗?现在我正在使用 reshape2 来实现此目的。

我想要“dplyr”解决方案:

require(reshape2)
data(iris)
dat <- melt(iris,id.vars="Species")

最佳答案

reshape2 的后继者是 tidyrmelt()dcast() 的等效项分别是 gather()spread()。相当于您的代码将是

library(tidyr)
data(iris)
dat <- gather(iris, variable, value, -Species)

如果您导入了 magrittr ,您可以使用管道运算符,如 dplyr 中,即写入

dat <- iris %>% gather(variable, value, -Species)

请注意,您需要显式指定变量和值名称,这与 melt() 不同。我发现 gather() 的语法非常方便,因为您可以只指定要转换为长格式的列,或者通过在它们前面添加前缀来指定要保留在新数据框中的列带有“-”(就像上面的 Species 一样),这比在 melt() 中键入要快一些。但是,我注意到至少在我的机器上,tidyr 明显比 reshape2 慢。

编辑 在回复下面@hadley 的评论时,我发布了一些时间信息来比较我的电脑上的两个功能。

library(microbenchmark)
microbenchmark(
melt = melt(iris,id.vars="Species"),
gather = gather(iris, variable, value, -Species)
)
# Unit: microseconds
# expr min lq median uq max neval
# melt 278.829 290.7420 295.797 320.5730 389.626 100
# gather 536.974 552.2515 567.395 683.2515 1488.229 100

set.seed(1)
iris1 <- iris[sample(1:nrow(iris), 1e6, replace = T), ]
system.time(melt(iris1,id.vars="Species"))
# user system elapsed
# 0.012 0.024 0.036
system.time(gather(iris1, variable, value, -Species))
# user system elapsed
# 0.364 0.024 0.387

sessionInfo()
# R version 3.1.1 (2014-07-10)
# Platform: x86_64-pc-linux-gnu (64-bit)
#
# locale:
# [1] LC_CTYPE=en_GB.UTF-8 LC_NUMERIC=C
# [3] LC_TIME=en_GB.UTF-8 LC_COLLATE=en_GB.UTF-8
# [5] LC_MONETARY=en_GB.UTF-8 LC_MESSAGES=en_GB.UTF-8
# [7] LC_PAPER=en_GB.UTF-8 LC_NAME=C
# [9] LC_ADDRESS=C LC_TELEPHONE=C
# [11] LC_MEASUREMENT=en_GB.UTF-8 LC_IDENTIFICATION=C

# attached base packages:
# [1] stats graphics grDevices utils datasets methods base
#
# other attached packages:
# [1] reshape2_1.4 microbenchmark_1.3-0 magrittr_1.0.1
# [4] tidyr_0.1
#
# loaded via a namespace (and not attached):
# [1] assertthat_0.1 dplyr_0.2 parallel_3.1.1 plyr_1.8.1 Rcpp_0.11.2
# [6] stringr_0.6.2 tools_3.1.1

关于r - 如何使用 dplyr 熔化和类型转换数据框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24880835/

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