当值为 txt 且新列为数字时如何转置

How to transpose when the value is a txt an the new column is a number

我有以下table

id  mycol counter
1   a      1
1   b      2
2   c      1
2   c      2
2   e      3

这就是我需要的

ID 1  2  3
1  a  b  done
2  c  c  done

我尝试使用 dcast 函数

mydata<-dcast(mydata, id~mycol, counter, value = 'mycol')

但是它不起作用,知道吗?

从你的问题看来,你正在尝试做一些事情,比如从长格式到宽格式的重塑。以下是如何使用 base R reshape() 来执行此操作:

mydata <- data.frame(id=c(1L,1L,2L,2L,2L),mycol=c('a','b','c','c','e'),counter=c(1L,2L,1L,2L,3L),stringsAsFactors=F);
reshape(mydata,dir='w',idvar='id',timevar='counter');
##   id mycol.1 mycol.2 mycol.3
## 1  1       a       b    <NA>
## 3  2       c       c       e

reshape() 不支持对结果列名进行如此精确的控制。之后您可以自己修复它们。假设你将上面的结果保存为res,你可以这样做:

colnames(res) <- sub(perl=T,'^mycol\.','',colnames(res));
res;
##   id 1 2    3
## 1  1 a b <NA>
## 3  2 c c    e