将R格式的数据帧重塑为宽格式

将R格式的数据帧重塑为宽格式,r,aggregate,formula,reshape2,R,Aggregate,Formula,Reshape2,我正在尝试使用restrape2包的dcast将长格式数据帧转换为宽格式。我的数据框看起来与下面的数据框类似 X = c(3,2,3,3,2,3,3,2,3) Y = c(-3, -1, -3, -3, -1, -3, -3, -1, -3) DATA = c(100, 200, 300, 400, 100, 500, 600, 200, 300) measurement = c("A", "A", "A", "B", "B", "B", "C", "C", "C") DF <- data

我正在尝试使用
restrape2
包的
dcast
将长格式数据帧转换为宽格式。我的数据框看起来与下面的数据框类似

X = c(3,2,3,3,2,3,3,2,3)
Y = c(-3, -1, -3, -3, -1, -3, -3, -1, -3)
DATA = c(100, 200, 300, 400, 100, 500, 600, 200, 300)
measurement = c("A", "A", "A", "B", "B", "B", "C", "C", "C")
DF <- data.frame(X, Y, DATA, measurement)
wideDF <- dcast(DF, X + Y ~ measurement, fun.aggregate = mean, value.var="DATA", drop = TRUE)
X=c(3,2,3,3,2,3,3,2,3)
Y=c(-3,-1,-3,-3,-1,-3,-3,-1,-3)
数据=c(100200300400100500600200300)
测量=c(“A”、“A”、“A”、“B”、“B”、“c”、“c”)

DF您可以将公式创建为字符串,然后使用
as.formula()

lhs
中,我使用
setdiff()
获取所有不是
DATA
measurement
的列名

library(重塑2)

lhs将
公式
参数设置为
dcast()
有一个特殊变量
,该变量“表示公式中未使用的所有其他变量”(
?重塑2::dcast
)。这对你的案子来说可能很方便。你的解决方案对我来说非常有效。谢谢
library(reshape2)
lhs <- paste0(setdiff(names(DF), c("DATA", "measurement")), collapse = "+")

dcast(DF, as.formula(paste0(lhs, "~ measurement")), fun.aggregate = mean, value.var = "DATA", drop = TRUE)
#   X  Y   A   B   C
# 1 2 -1 200 100 200
# 2 3 -3 200 450 450