用于dcast'ing data.frame的公式

用于dcast'ing data.frame的公式,r,reshape,reshape2,dcast,R,Reshape,Reshape2,Dcast,我有一个带有colname的data.frame:A01,A02,…,A25,…,Z01,…,Z25总共26*25。例如: set.seed(1) df <- data.frame(matrix(rnorm(26*25),ncol=26*25,nrow=1)) cols <- c(paste("0",1:9,sep=""),10:25) colnames(df) <- c(sapply(LETTERS,function(l) paste(l,cols,sep=""))) 我想

我有一个带有colname的data.frame:A01,A02,…,A25,…,Z01,…,Z25总共26*25。例如:

set.seed(1)
df <- data.frame(matrix(rnorm(26*25),ncol=26*25,nrow=1))
cols <- c(paste("0",1:9,sep=""),10:25)
colnames(df) <- c(sapply(LETTERS,function(l) paste(l,cols,sep="")))

我想把它播送到一个数据框中。26x25行的帧是a-Z,列是01-25。知道这个dcast的公式是什么吗?

删除列看起来不太好,仍然在学习data.table。需要有人把它弄漂亮

# convert to data.table
df <- data.table(df)

# melt all the columns first
test <- melt(df, measure.vars = names(df))

# split the original column name by letter
# paste the numbers together
# then remove the other columns
test[ , c("ch1", "ch2", "ch3") := tstrsplit(variable, "")][ , "ch2" := 
paste(ch2, ch3, sep = "")][ , c("ch3", "variable") := NULL]

# dcast with the letters (ch1) as rows and numbers (ch2) as columns
dcastOut <- dcast(test, ch1 ~ ch2 , value.var = "value")
然后删除包含数字的第一列

我们可以使用tidyverse


您要查找的公式可以来自melt的data.table实现中的patterns参数。dcast用于从长形到宽形,而melt用于从宽形到长形。melt不使用公式方法

基本上,您需要执行以下操作:

library(data.table)
setDT(df)                     ## convert to a data.table
cols <- sprintf("%02d", 1:25) ## Easier way for you to make cols in the future
melt(df, measure.vars = patterns(cols), variable.name = "ID")[, ID := LETTERS][]

使用base R REFORMATE,您可以从REFORMATEDF开始,方向=long,sep=,VARINGING=TRUE,timevar=NULLWAY melt data.table首先获取两列,即值和原始列名。然后,使用tstrsplit将字母和数字分开,然后将数字粘贴在一起,然后使用dcast。这是个坏主意吗?@din-我觉得这是个合理的解决办法。
library(data.table)
setDT(df)                     ## convert to a data.table
cols <- sprintf("%02d", 1:25) ## Easier way for you to make cols in the future
melt(df, measure.vars = patterns(cols), variable.name = "ID")[, ID := LETTERS][]