英文:
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 %>%
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论