1

我有一个data.framecolnamesA01、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="")))

我想要dcast它到data.frame26x25 (行将是 AZ 和列 01-25)。知道这个公式是dcast什么吗?

4

3 回答 3

1

删除列看起来不太好(仍在学习 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")

然后只需删除包含数字的第一列?

于 2017-05-22T05:26:53.097 回答
1

我们可以用tidyverse

library(tidyverse)
res <- gather(df) %>%
           group_by(key = sub("\\D+", "", key))  %>% 
           mutate(n = row_number()) %>%
           spread(key, value) %>%
           select(-n)
dim(res)
#[1] 26 25
于 2017-05-22T06:16:52.553 回答
1

您正在寻找的“公式”可以来自patterns“data.table”实现中的参数meltdcast用于从“长”形式变为“宽”形式,而melt用于从宽形式变为长(er)形式。melt()不使用formula方法。

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

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][]
于 2018-01-10T18:03:19.510 回答