【发布时间】:2017-05-23 10:06:49
【问题描述】:
我正在尝试在长表上应用dcast,继续线程答案How to get this data structure in R?
代码
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)
输出
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
预期输出:通过测试函数ggplot
测试 Uwe 的提议
目的是得到这个数据结构
dat.m <- structure(c(150L, 60L, 41L, 61L, 0L, 0L), .Dim = c(3L, 2L), .Dimnames = list(c("ave_max", "ave", "lepo"), NULL))
来自这个数据结构
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))
尝试
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))
# ...
-
代码和输出
dat.m <- setDT(dat.m)输出错误
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> -
代码和输出
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);输出错误
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(向后移植)
操作系统:Debian 8.7。
【问题讨论】:
-
请删除对
library("reshape2")的调用,因为data.table有自己的melt()和dcast()的快速实现。 -
如果您 (1) 编辑 Q 的重要部分,(2) 对不同的对象使用相同的变量名称
dat.m,则很难回答您的问题。对于矩阵对象,最好使用dat.m,对于 data.frame 对象,最好使用dat.df。我在下面的答案已经过测试,可以产生给定数据所示的结果。
标签: r data-structures