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

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

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

问题

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

  1. Class Gluc
  2. 1 3.7
  3. 1 3.8
  4. 1 3.5
  5. 1 3.9
  6. 4 4.2
  7. 4 5.1
  8. 4 5.8
  9. 4 4.9
  10. 4 5.7
  11. 9 6.6
  12. 9 6.9
  13. 9 8.1
  14. 9 8.8
  15. 11 7.4
  16. 11 8.3
  17. 11 9.8

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

  1. 1 4 9 11
  2. 3.7 4.2 6.6 7.4
  3. 3.8 5.1 6.9 8.3
  4. 3.5 5.8 8.1 9.8
  5. 3.9 4.9 8.8
  6. 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;

  1. Class Gluc
  2. 1 3.7
  3. 1 3.8
  4. 1 3.5
  5. 1 3.9
  6. 4 4.2
  7. 4 5.1
  8. 4 5.8
  9. 4 4.9
  10. 4 5.7
  11. 9 6.6
  12. 9 6.9
  13. 9 8.1
  14. 9 8.8
  15. 11 7.4
  16. 11 8.3
  17. 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. 1 4 9 11
  2. 3.7 4.2 6.6 7.4
  3. 3.8 5.1 6.9 8.3
  4. 3.5 5.8 8.1 9.8
  5. 3.9 4.9 8.8
  6. 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 进行分组并添加行号:

  1. library(dplyr)
  2. library(tidyr)
  3. df %>%
  4. group_by(Class) %>%
  5. mutate(id = row_number()) %>%
  6. pivot_wider(names_from = Class, values_from = Gluc) %>%
  7. select(-id)
  1. `1` `4` `9` `11`
  2. <dbl> <dbl> <dbl> <dbl>
  3. 1 3.7 4.2 6.6 7.4
  4. 2 3.8 5.1 6.9 8.3
  5. 3 3.5 5.8 8.1 9.8
  6. 4 3.9 4.9 8.8 NA
  7. 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:

  1. library(dplyr)
  2. library(tidyr)
  3. df %&gt;%
  4. group_by(Class) %&gt;%
  5. mutate(id = row_number()) %&gt;%
  6. pivot_wider(names_from = Class, values_from = Gluc) %&gt;%
  7. select(-id)
  1. `1` `4` `9` `11`
  2. &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt;
  3. 1 3.7 4.2 6.6 7.4
  4. 2 3.8 5.1 6.9 8.3
  5. 3 3.5 5.8 8.1 9.8
  6. 4 3.9 4.9 8.8 NA
  7. 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:

确定