gpt4 book ai didi

reshape 但扩展 R 中的数据

转载 作者:行者123 更新时间:2023-12-04 09:25:43 28 4
gpt4 key购买 nike

我有以下数据集:

my.data <- read.table(text = '
ID tmc_code wDay time_category TTTR
1 121-04711 weekday Afternoon 1.1
2 121-04711 weekend Evening 1.3
3 121-04711 weekday Morning 1.1
4 121-04712 weekend Afternoon 1.101626016
5 121-04712 weekday Evening 1.281124498
6 121-04712 weekday Morning 1.080645161
', header = TRUE, stringsAsFactors = FALSE, na.strings = 'NA')
my.data

我想要一个像这样的宽格式结果:
#result
# tmc_code wDay TTTR_afternnon TTTR_Evening TTTR_Morning
# 121-04711 weekday 1.1 1.3 NA
# 121-04711 weekend NA NA 1.1
# 121-04712 weekday NA 1.281124498 1.080645161
# 121-04712 weekend 1.101626016 NA NA

我们可以看到 hat 不仅要使用 reshape 函数,而且实际上这个过程会将 6 个数据变成 9 个数据。

下面的 reshape 函数不适用于这种情况:
w.my.data <- reshape(my.data, idvar = "tmc_code", timevar = "time_category", direction = "wide")

我想知道有人有更好的想法吗?非常感激!

最佳答案

您可以使用 reshape2 包:

> reshape2::dcast(my.data, tmc_code + wDay ~ paste("TTTR", time_category, sep="_"))

Using TTTR as value column: use value.var to override.
tmc_code wDay TTTR_Afternoon TTTR_Evening TTTR_Morning
1 121-04711 weekday 1.100000 NA 1.100000
2 121-04711 weekend NA 1.300000 NA
3 121-04712 weekday NA 1.281124 1.080645
4 121-04712 weekend 1.101626 NA NA

哦,显然它适用于 reshape同样,这也给出了有关此处忽略的 ID 变化的有用警告:
> reshape(my.data, idvar = c("tmc_code", "wDay"), timevar = "time_category", v.names = "TTTR", direction = "wide")

ID tmc_code wDay TTTR.Afternoon TTTR.Evening TTTR.Morning
1: 1 121-04711 weekday 1.100000 NA 1.100000
2: 2 121-04711 weekend NA 1.300000 NA
3: 4 121-04712 weekend 1.101626 NA NA
4: 5 121-04712 weekday NA 1.281124 1.080645
Warning message:
In reshapeWide(data, idvar = idvar, timevar = timevar, varying = varying, :
some constant variables (ID) are really varying

关于 reshape 但扩展 R 中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52768640/

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