Skip to content

Instantly share code, notes, and snippets.

@mrdwab
Created May 13, 2015 03:56
Show Gist options
  • Select an option

  • Save mrdwab/f500417924f62fdb2b13 to your computer and use it in GitHub Desktop.

Select an option

Save mrdwab/f500417924f62fdb2b13 to your computer and use it in GitHub Desktop.
dt <- data.table(
Row = c(rep(1, 3), rep(2, 3), 3),
Col = factor(c(1, 2, 8, 1, 2, 9, 2), 1:9),
Value = c(31L, 56L, 13L, 83L,51L, 16L, 53L)
)
str(dt)
# Classes ‘data.table’ and 'data.frame': 7 obs. of 3 variables:
# $ Row : num 1 1 1 2 2 2 3
# $ Col : Factor w/ 9 levels "1","2","3","4",..: 1 2 8 1 2 9 2
# $ Value: int 31 56 13 83 51 16 53
# - attr(*, ".internal.selfref")=<externalptr>
dcast.data.table(dt, Row ~ Col, value.var = "Value", drop = FALSE)
# Row 1 2 8 9
# 1: 1 31 56 13 NA
# 2: 2 83 51 NA 16
# 3: 3 NA 53 NA NA
dcast.data.table(dt, Row ~ Col, value.var = "Value", drop = FALSE, fun.aggregate = I)
# Error in dcast.data.table(dt, Row ~ Col, value.var = "Value", drop = FALSE, :
# Aggregating function provided to argument 'fun.aggregate' should always return a length 1 vector, but returns 0-length value for fun.aggregate(integer(0)). This value will have to be used to fill missing combinations, if any, and therefore can not be of length 0. Either override by setting the 'fill' argument explicitly or modify your function to handle this case appropriately.
dcast.data.table(dt, Row ~ Col, value.var = "Value", drop = FALSE, fun.aggregate = I, fill = NA_integer_)
# Row 1 2 8 9
# 1: 1 31 56 13 NA
# 2: 2 83 51 NA 16
# 3: 3 NA 53 NA NA
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment