I am trying to apply dcast
on long table, continua from the thread answer How to get this data structure in R?
Code
dat.m <- structure(c(150L, 60L, 41L, 61L, 0L, 0L), .Dim = c(3L, 2L), .Dimnames = list(
c("ave_max", "ave", "lepo"), NULL))
library("ggplot2")
library("data.table")
dat.m <- melt(as.data.table(dat.m, keep.rownames = "Vars"), id.vars = "Vars") # https://stackoverflow.com/a/44128640/54964
dat.m
print("New step")
# http://stackoverflow.com/a/44090815/54964
minmax <- dat.m[dat.m$Vars %in% c("ave_max","lepo"), ]
absol <- dat.m[dat.m$Vars %in% c("ave"), ]
#minm <- dcast(minmax, Vars ~ variable)
minm <- dcast(minmax, Vars ~ ...)
absol <- merge(absol, minm, by = "Vars", all.x = T)
absol
#Test function
ggplot(absol, aes(x = Vars, y = value, fill = variable)) +
geom_bar(stat = "identity") +
geom_errorbar(aes(ymin = lepo, ymax = ave_max), width = .25)
Output
dcast, melt
Vars variable value
1: ave_max V1 150
2: ave V1 60
3: lepo V1 41
4: ave_max V2 61
5: ave V2 0
6: lepo V2 0
[1] "New step"
Vars variable value V1 V2
1: ave V1 60 NA NA
2: ave V2 0 NA NA
Error in FUN(X[[i]], ...) : object 'lepo' not found
Calls: <Anonymous> ... by_layer -> f -> <Anonymous> -> f -> lapply -> FUN -> FUN
Execution halted
Expected output: to pass the test function ggplot
Testing Uwe's proposal
Aim is to get to this data structure
dat.m <- structure(c(150L, 60L, 41L, 61L, 0L, 0L), .Dim = c(3L, 2L), .Dimnames = list(c("ave_max", "ave", "lepo"), NULL))
from this data structure
dat.m <- structure(list(ave_max = c(15L, 6L), ave = c(6L, NA), lepo = c(4L, NA)), .Names = c("ave_max", "ave", "lepo"), class = "data.frame", row.names = c(NA, -2L))
Attempts
dat.m <- structure(list(ave_max = c(15L, 6L), ave = c(6L, NA), lepo = c(4L, NA)), .Names = c("ave_max", "ave", "lepo"), class = "data.frame", row.names = c(NA, -2L))
# ...
Code and output
dat.m <- setDT(dat.m)
Output wrong
ave_max ave lepo 1: 15 6 4 2: 6 NA NA Classes ‘data.table’ and 'data.frame': 2 obs. of 3 variables: $ ave_max: int 15 6 $ ave : int 6 NA $ lepo : int 4 NA - attr(*, ".internal.selfref")=<externalptr>
Code and output
dat.m <- as.matrix(dcast(melt(setDT(dat.m), measure.vars = names(dat.m)), variable ~ rowid(variable))[, variable := NULL]); dimnames(dat.m) <- list(names(dat.m), NULL);
Output wrong
Error in `:=`(variable, NULL) : Check that is.data.table(DT) == TRUE. Otherwise, := and `:=`(...) are defined for use in j, once only and in particular ways. See help(":=").
R: 3.4.0 (backports)
OS: Debian 8.7.