R-将2列数据帧重塑为多列矩阵 [英] R - reshaping 2 column data frame to multiple column matrix

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

问题描述

很抱歉,如果这个问题是重复的,但我找不到它.

Apologies if this question is a repeat but I couldn't find it.

我希望以以下形式重塑数据框(从read_bulk中读取):

I am looking to reshape a data frame in the form (read in from read_bulk):

"name.a", 5
"name.a", 4
"name.a", 1
"name.b", 2
"name.b", 3
"name.b", 2
"name.c", 1
"name.c", 5
"name.c", 6

更改为以下形式:

5, 4, 1
2, 3, 2
1, 5, 6

实际数据框的每个名称包含数千个数字,我不知道每个名称中的数字,但它们都是相等的.每个名称在最终形式中均应为不同的行.

The real data frame consists of thousands of numbers for each name, I do not know the number in each but they are all equal. Each name is to be a different row in the final form.

我尝试重塑了它,但是似乎无法使它起作用,有什么想法吗?

I attempted this with reshape but couldn't seem to get this to work, any thoughts?

推荐答案

 unstack(dat,V2~V1)
  name.a name.b name.c
1      5      2      1
2      4      3      5
3      1      2      6

使用其他库:

library(tidyverse)
dat%>%group_by(V1)%>%mutate(id2=1:n())%>%spread(id2,V2)
# A tibble: 3 x 4
# Groups:   V1 [3]
      V1   `1`   `2`   `3`
*  <chr> <int> <int> <int>
1 name.a     5     4     1
2 name.b     2     3     2
3 name.c     1     5     6

数据:

dat=read.table(h=F,sep=",",stringsAsFactors = F,strip.white = T,text=' "name.a", 5
"name.a", 4
               "name.a", 1
               "name.b", 2
               "name.b", 3
               "name.b", 2
               "name.c", 1
               "name.c", 5
               "name.c", 6')

这篇关于R-将2列数据帧重塑为多列矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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