将数据帧的不同行转换为 R 中的一行
我有一个看起来像这样的数据集:
CATA 1 10101
CATA 2 11101
CATA 3 10011
CATB 1 10100
CATB 2 11100
CATB 3 10011
等等
,我想将这些不同的行组合成一个长行,如下所示:
CATA 101011110110011
CATB 101001110010011
我尝试过使用 Melt() 然后使用 dcast() 来执行此操作,但似乎没有去工作。有人有一些简单的代码可以做到这一点吗?
I have a dataset that looks like this:
CATA 1 10101
CATA 2 11101
CATA 3 10011
CATB 1 10100
CATB 2 11100
CATB 3 10011
etc.
and I want to combine these different rows into a single, long row like this:
CATA 101011110110011
CATB 101001110010011
I've tried doing this with melt() and then dcast(), but it doesn't seem to work. Does anyone have some simple pieces of code to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
查看
paste
命令,特别是collapse
参数。目前尚不清楚如果/当第一列有不同的值时会发生什么,所以我不会冒险猜测。如果您遇到困难,请更新您的问题。请注意,您可能希望首先将数据转换为字符,以防止前导零被修剪。
编辑:解决第一列的多个值
使用
plyr
的ddply
函数,该函数需要 data.frame 作为输入和分组变量(s)。然后,我们使用与之前相同的paste()
技巧以及summarize()
。Look at the
paste
command and specifically thecollapse
argument. It's not clear what should happen if/when you have different values for the first column, so I won't venture to guess. Update your question if you get stuck.Note that you may want to convert the data to character first to prevent leading zeros from being trimmed.
EDIT: to address multiple values for the first column
Use
plyr
'sddply
function which expects a data.frame as an input and a grouping variable(s). We then use the samepaste()
trick as before along withsummarize()
.假设
dat
的V1
中所有可能的元素都已知,@Chase 的答案要好得多!
Assuming all possible elements in
V1
ofdat
are known,@Chase answer is much better !