在使用dcast时,如何基于列'Col'指定列顺序?
df <- dcast(x, ID ~ ColumnName, value.var = "Answer")
我需要解决方案不特定于数据,因为x可以是任何问题的结果(因此Col可以是1-3或1-2等)。下面是x的两个虚拟示例。
ID Answer ColumnName Col
1 Anduin First Name 1
1 Wrynn Surname 2
1 Alliance Faction 3
2 Sylvanas First Name 1
2 Windrunner Surname 2
2 Horde Faction 3
ID Answer ColumnName Col
1 The Kirin Tor Quest 1
1 90 Level 2
2 Emissary Quest 1
2 38 Level 2
答案 0 :(得分:0)
我没有看到dcast
参数可以指定列的最终顺序,但是始终可以将结果子集化。
fun_dcast <- function(DF, formula = ID ~ ColumnName, value.var = "Answer"){
reshape2::dcast(DF, formula, value.var = value.var)[c(1, 1 + unique(DF[["Col"]]))]
}
fun_dcast(x1)
# ID Faction First Name Surname
#1 1 Alliance Anduin Wrynn
#2 2 Horde Sylvanas Windrunner
fun_dcast(x2)
# ID Level Quest
#1 1 90 The Kirin Tor
#2 2 38 Emissary
数据。
x1 <- read.table(text = "
ID Answer ColumnName Col
1 Anduin 'First Name' 1
1 Wrynn Surname 2
1 Alliance Faction 3
2 Sylvanas 'First Name' 1
2 Windrunner Surname 2
2 Horde Faction 3
", header = TRUE)
x2 <- read.table(text = "
ID Answer ColumnName Col
1 'The Kirin Tor' Quest 1
1 90 Level 2
2 Emissary Quest 1
2 38 Level 2
", header = TRUE)
答案 1 :(得分:0)
pickle
和help("dcast", "reshape2")
中都没有很好的文档记录,但是如果help("dcast", "data.table")
是一个因数,则这些列按因数级别排序。
ColumnName
各列按字母顺序排列,与factor()
Col
# create sample dataset x <- readr::read_table( "ID Answer ColumnName Col 1 Anduin First Name 1 1 Wrynn Surname 2 1 Alliance Faction 3 2 Sylvanas First Name 1 2 Windrunner Surname 2 2 Horde Faction 3") reshape2::dcast(x, ID ~ ColumnName, value.var = "Answer")
ID Faction First Name Surname
1 1 Alliance Anduin Wrynn
2 2 Horde Sylvanas Windrunner
和factor()
这些列按从reorder()
得出的因子水平进行排序
Col
library(magrittr) # not essential; just used to improve readabilty x$ColumnName <- with(x, factor(ColumnName, levels = unique(ColumnName)) %>% reorder(Col)) reshape2::dcast(x, ID ~ ColumnName, value.var = "Answer")