使用 dcast 在 R 中重塑数据
Reshape data in R using dcast
我有以下数据
library(reshape2)
d <- data_frame(
Quart = c("Q1", "Q2", "Q3", "Q4", "Q4", "Q1","Q4","Q1", "Q2", "Q3"),
var1 = c(1,0,1,1,1,0,2,3,0,1),
var2= c(1,0,1,1,1,0,1,0,1,0),
location= c("loc1", "loc1", "loc2", "loc2", "loc2", "loc2", "loc2",
"loc1", "loc2","loc1"))
我想重塑这些数据以创建如下所示的 table。
加星标的单元格应为 var1 乘以 loc1 的数量,其中 Quart=Q1。所以在这种情况下,它会是“3”,loc2 会是“0”,因为没有任何行同时具有 Q1 和 loc2,loc3 会是“1”,loc4 会是“0”。
我尝试使用 d cast 重塑数据:
d%>%
reshape2::dcast(formula = Quart * var1 ~ location
,fun.aggregate = length
translates to counts
,margins = c("Quart", "var1")
) -> d
然而,这并不能完全满足我的需求。有什么想法吗?
谢谢
一种选择是先使用tidyr::gather
将var1
和var2
转换为长格式,然后将dcast
应用为:
library(reshape2)
library(tidyverse)
gather(d, key, value, -Quart, -location) %>%
dcast(Quart+key ~ location, fun.aggregate = sum, value.var = "value")
# Quart key loc1 loc2
# 1 Q1 var1 4 0
# 2 Q1 var2 1 0
# 3 Q2 var1 0 0
# 4 Q2 var2 0 1
# 5 Q3 var1 1 1
# 6 Q3 var2 0 1
# 7 Q4 var1 0 4
# 8 Q4 var2 0 3
我有以下数据
library(reshape2)
d <- data_frame(
Quart = c("Q1", "Q2", "Q3", "Q4", "Q4", "Q1","Q4","Q1", "Q2", "Q3"),
var1 = c(1,0,1,1,1,0,2,3,0,1),
var2= c(1,0,1,1,1,0,1,0,1,0),
location= c("loc1", "loc1", "loc2", "loc2", "loc2", "loc2", "loc2",
"loc1", "loc2","loc1"))
我想重塑这些数据以创建如下所示的 table。
加星标的单元格应为 var1 乘以 loc1 的数量,其中 Quart=Q1。所以在这种情况下,它会是“3”,loc2 会是“0”,因为没有任何行同时具有 Q1 和 loc2,loc3 会是“1”,loc4 会是“0”。
我尝试使用 d cast 重塑数据:
d%>%
reshape2::dcast(formula = Quart * var1 ~ location
,fun.aggregate = length
translates to counts
,margins = c("Quart", "var1")
) -> d
然而,这并不能完全满足我的需求。有什么想法吗?
谢谢
一种选择是先使用tidyr::gather
将var1
和var2
转换为长格式,然后将dcast
应用为:
library(reshape2)
library(tidyverse)
gather(d, key, value, -Quart, -location) %>%
dcast(Quart+key ~ location, fun.aggregate = sum, value.var = "value")
# Quart key loc1 loc2
# 1 Q1 var1 4 0
# 2 Q1 var2 1 0
# 3 Q2 var1 0 0
# 4 Q2 var2 0 1
# 5 Q3 var1 1 1
# 6 Q3 var2 0 1
# 7 Q4 var1 0 4
# 8 Q4 var2 0 3