如何根据R中的特定列号更改数据框的设计?

huangapple go评论53阅读模式
英文:

How can I change the design of a data frame according to a particular column numbers in R?

问题

我需要根据特定的列数重新整理我的数据框。我的数据框有2列和1127行,如下所示:

     Class    Gluc
     1         3.7
     1         3.8
     1         3.5
     1         3.9
     4         4.2
     4         5.1
     4         5.8
     4         4.9
     4         5.7
     9         6.6 
     9         6.9
     9         8.1
     9         8.8
     11        7.4
     11        8.3
     11        9.8

我想要将第1列(Class)中的数字作为列名,并根据它们的类别号将葡萄糖值对齐在这些新列下面。如下所示:

     1     4     9     11
    3.7   4.2   6.6   7.4
    3.8   5.1   6.9   8.3
    3.5   5.8   8.1   9.8
    3.9   4.9   8.8
          5.7

我尝试使用 "group_by" 和 "mutate" 函数,但它们没有起作用,而且它们创建了一个列表。我想要一个数据框而不是一个列表。如果有人能帮助我,我将非常感激。

英文:

I need to reshape my data frame according to the particular column numbers. My data frame has 2 columns and 1127 rows and it is like that;

 Class    Gluc
 1         3.7
 1         3.8
 1         3.5
 1         3.9
 4         4.2
 4         5.1
 4         5.8
 4         4.9
 4         5.7
 9         6.6 
 9         6.9
 9         8.1
 9         8.8
 11        7.4
 11        8.3
 11        9.8

I want to do that the numbers in column 1 (Class) will be column names and glucose values will be align under these new column numbers according to their class number. Like this;

 1     4     9     11
3.7   4.2   6.6   7.4
3.8   5.1   6.9   8.3
3.5   5.8   8.1   9.8
3.9   4.9   8.8
      5.7

I used "group_by" and "mutate" functions but they didn't work and also they create a list. I want a data frame not a list.
If someone help me I will be very appreciated..

答案1

得分: 0

我们可以使用 pivot_wider() 进行操作,以使其运行顺畅,首先按 Class 进行分组并添加行号:

library(dplyr)
library(tidyr)

df %>%
  group_by(Class) %>%
  mutate(id = row_number()) %>%
  pivot_wider(names_from = Class, values_from = Gluc) %>%
  select(-id)
   `1`   `4`   `9`  `11`
  <dbl> <dbl> <dbl> <dbl>
1   3.7   4.2   6.6   7.4
2   3.8   5.1   6.9   8.3
3   3.5   5.8   8.1   9.8
4   3.9   4.9   8.8  NA  
5  NA     5.7  NA    NA 
英文:

We could do it with pivot_wider() to get it work smooth we first group by Class and add row numbers:

library(dplyr)
library(tidyr)

df %&gt;%
  group_by(Class) %&gt;% 
  mutate(id = row_number()) %&gt;% 
  pivot_wider(names_from = Class, values_from = Gluc) %&gt;% 
  select(-id)
   `1`   `4`   `9`  `11`
  &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt;
1   3.7   4.2   6.6   7.4
2   3.8   5.1   6.9   8.3
3   3.5   5.8   8.1   9.8
4   3.9   4.9   8.8  NA  
5  NA     5.7  NA    NA 

huangapple
  • 本文由 发表于 2023年5月23日 01:46:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76308738.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定