当值为txt时如何转置,新列是一个数字?

时间:2021-08-19 21:28:49

I have the following table

我有下表。

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

And this is what I neee

这就是我需要的。

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

I try to use the dcast function

我尝试使用dcast函数。

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

but It's not working, any idea?

但它不起作用,有什么想法吗?

1 个解决方案

#1


0  

It appears from your question that you're trying to do something like a reshaping from long to wide format. Here's how you can use base R reshape() to do this:

从你的问题看来,你正试图做一些类似于从长到宽格式的重塑。下面是如何使用base R重塑()来实现这一点:

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() does not support such precise control over the resulting column names. You can fix them up yourself afterward. Assuming you saved the above result as res, you can do this:

整形()不支持对结果列名的精确控制。之后你可以自己修理。假设您将上述结果保存为res,您可以这样做:

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

#1


0  

It appears from your question that you're trying to do something like a reshaping from long to wide format. Here's how you can use base R reshape() to do this:

从你的问题看来,你正试图做一些类似于从长到宽格式的重塑。下面是如何使用base R重塑()来实现这一点:

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() does not support such precise control over the resulting column names. You can fix them up yourself afterward. Assuming you saved the above result as res, you can do this:

整形()不支持对结果列名的精确控制。之后你可以自己修理。假设您将上述结果保存为res,您可以这样做:

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