使用R将数据帧的多行转换为多列的一行 [英] Transform multiple rows of a data frame into one row with multiple columns with R

查看:67
本文介绍了使用R将数据帧的多行转换为多列的一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含四列的数据框:

I have a data frame with four columns :

df=data.frame( UserId=c(1,2,2,2,3,3), CatoId=c('C','A','B','C','D','E'), No=c(1,9,2,2,5,3))  

UserId CatoId No  
1       C     1  
2       A     9  
2       B     2  
2       C     2  
3       D     5  
3       E     3

我想将结构转换为以下结构:

I would like to transform the structure into the following one :

UserId A B C D E  
  1    0 0 1 0 0  
  2    9 2 2 0 0 
  3    0 0 0 5 3

其中的列代表CatoId中所有可能的值.
第一个数据帧具有200万行,CatoId具有21个不同的值.所以我不想使用任何循环.有没有用R做到这一点的方法.否则,最佳的进行方法是什么?
我的目标是在最后一个数据帧上应用聚类算法.

Where the columns represents all possible values in CatoId.
The first data frame has 2 million rows and CatoId has 21 different values. So I don't want to use any loops. Is there a way to do this with R. Otherwise what is the best way to proceed?
My goal would be to apply a clustering algorithm on the last dataframe.

推荐答案

您可以使用dcast:

df1 <- dcast(df, UserId ~ CatoId, value.var = "No", fill = 0)

这篇关于使用R将数据帧的多行转换为多列的一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆