## --- Basic usage --------------------------------------------------
long <- data.frame(
id = rep(1:3, each = 2),
variable = rep(c("x", "y"), 3),
value = c(1, 2, 3, 4, 5, 6)
)
dcast(long, id = "id", variable = "variable", value = "value")
## --- Formula interface --------------------------------------------
dcast(long, formula = id ~ variable)
## --- Multiple id columns ------------------------------------------
long2 <- data.frame(
year = rep(2020:2021, each = 4),
city = rep(c("A", "B"), each = 2, times = 2),
variable = rep(c("temp", "rain"), 4),
value = c(15.2, 210, 14.8, 180, 16.1, 230, 15.5, 195)
)
# Explicit id columns
dcast(long2, id = c("year", "city"),
variable = "variable", value = "value")
# Formula form (equivalent)
dcast(long2, formula = year + city ~ variable)
## --- Fill missing cells -------------------------------------------
# (2, "y") is missing from the input; fill = 0 gives it 0.
long3 <- data.frame(
id = c(1, 1, 2),
variable = c("x", "y", "x"),
value = c(1, 2, 3)
)
dcast(long3, id = "id",
variable = "variable", value = "value",
fill = 0)
## --- Aggregate duplicate (id, variable) pairs ---------------------
# id = 1 appears twice with variable = "x"; the mean is 1.5.
long4 <- data.frame(
id = c(1, 1, 2),
variable = c("x", "x", "x"),
value = c(1, 2, 3)
)
dcast(long4, id = "id",
variable = "variable", value = "value",
fun.aggregate = mean)
# sum and length work the same way
dcast(long4, id = "id",
variable = "variable", value = "value",
fun.aggregate = sum)
## --- Skip NA values during scatter --------------------------------
long5 <- data.frame(
id = c(1, 1, 2, 2),
variable = c("x", "y", "x", "y"),
value = c(1, NA, 3, 4)
)
# Default: NA stays as NA
dcast(long5, id = "id",
variable = "variable", value = "value")
# na.rm = TRUE: (1, "y") is skipped, cell keeps the fill value
dcast(long5, id = "id",
variable = "variable", value = "value",
na.rm = TRUE, fill = -1)
## --- Round-trip with melt() ---------------------------------------
wide <- data.frame(id = 1:3, a = c(1.5, 2.5, 3.5), b = c(4.5, 5.5, 6.5))
back <- dcast(melt(wide, id.vars = "id"),
id = "id", variable = "variable", value = "value")
back[order(back$id), ]
## --- Larger example: 1000 rows, 50 levels -------------------------
set.seed(1)
n_rows <- 1000L
n_levels <- 50L
long_big <- data.frame(
id = rep(seq_len(n_rows / n_levels), each = n_levels),
variable = rep(sprintf("v%02d", seq_len(n_levels)),
times = n_rows / n_levels),
value = rnorm(n_rows)
)
wide_big <- dcast(long_big, id = "id",
variable = "variable", value = "value")
dim(wide_big)
Run the code above in your browser using DataLab