使用没有聚合函数的 Reshape2 在 R 中从长到宽重塑 DF
Reshape DF from long to wide in R using Reshape2 without an aggregation function
我处理的数据中的一个常见任务是将客户端数据从长数据重塑为宽数据。我有一个使用下面概述的 Reshape 来执行此操作的过程,它基本上创建了新的(但未修改的)列,并附加了数字索引。就我而言,我不想对数据进行任何修改。我的问题是,因为我经常将 reshape2 用于其他操作,所以这是如何用 dcast 完成的?例如,示例数据似乎不需要被 id 融化,但我不确定我将如何让它变宽。任何人都能够在 reshape2 中提供代码以生成与下面示例中的 "wide" 相当的框架吗?
谢谢。
例子
date_up <- as.numeric(as.Date("1990/01/01"))
date_down <- as.numeric(as.Date("1960/01/01"))
ids <- data.frame(id=rep(1:1000, 3),site=rep(c("NMA", "NMB","NMC"), 1000))
ids <- ids[order(ids$id), ]
dates <- data.frame(datelast=runif(3000, date_down, date_up),
datestart=runif(3000, date_down, date_up),
dateend=runif(3000, date_down, date_up),
datemiddle=runif(3000, date_down, date_up))
dates[] <- lapply(dates[ , c("datestart", "dateend", "datemiddle")],
as.Date.numeric, origin = "1970-01-01")
df <- cbind(ids, dates)
# Make a within group index and reshape df
df$gid <- with(df, ave(rep(1, nrow(df)), df[,"id"], FUN = seq_along))
wide <- reshape(df, idvar = "id", timevar = "gid", direction = "wide")
我们可以使用 data.table
中的 dcast
,它可以包含多个 value.var
列。将 'data.frame' 转换为 'data.table' (setDT(df)
),使用带公式的 dcast
和指定的 value.var
。
library(data.table)
dcast(setDT(df), id~gid, value.var=names(df)[2:6])
注意:data.table
方法比 reshape2
方法更快
我处理的数据中的一个常见任务是将客户端数据从长数据重塑为宽数据。我有一个使用下面概述的 Reshape 来执行此操作的过程,它基本上创建了新的(但未修改的)列,并附加了数字索引。就我而言,我不想对数据进行任何修改。我的问题是,因为我经常将 reshape2 用于其他操作,所以这是如何用 dcast 完成的?例如,示例数据似乎不需要被 id 融化,但我不确定我将如何让它变宽。任何人都能够在 reshape2 中提供代码以生成与下面示例中的 "wide" 相当的框架吗?
谢谢。
例子
date_up <- as.numeric(as.Date("1990/01/01"))
date_down <- as.numeric(as.Date("1960/01/01"))
ids <- data.frame(id=rep(1:1000, 3),site=rep(c("NMA", "NMB","NMC"), 1000))
ids <- ids[order(ids$id), ]
dates <- data.frame(datelast=runif(3000, date_down, date_up),
datestart=runif(3000, date_down, date_up),
dateend=runif(3000, date_down, date_up),
datemiddle=runif(3000, date_down, date_up))
dates[] <- lapply(dates[ , c("datestart", "dateend", "datemiddle")],
as.Date.numeric, origin = "1970-01-01")
df <- cbind(ids, dates)
# Make a within group index and reshape df
df$gid <- with(df, ave(rep(1, nrow(df)), df[,"id"], FUN = seq_along))
wide <- reshape(df, idvar = "id", timevar = "gid", direction = "wide")
我们可以使用 data.table
中的 dcast
,它可以包含多个 value.var
列。将 'data.frame' 转换为 'data.table' (setDT(df)
),使用带公式的 dcast
和指定的 value.var
。
library(data.table)
dcast(setDT(df), id~gid, value.var=names(df)[2:6])
注意:data.table
方法比 reshape2