R 将一列展开为多列
我有一列“m”,其中包含与一个主题(ID)关联的多个值。我需要将此列中的值分散在5个不同的列中,以获得下面提供的第二个表。我还需要将名称与这些列相关联R 将一列展开为多列,r,function,dplyr,spread,R,Function,Dplyr,Spread,我有一列“m”,其中包含与一个主题(ID)关联的多个值。我需要将此列中的值分散在5个不同的列中,以获得下面提供的第二个表。我还需要将名称与这些列相关联 f <- read.table(header = TRUE, text = " Scale ID m 1 1 1 0.4089795 2 1 1 0.001041055 3 1 1 0.1843616 4 1 1 0.03398921 5
f <- read.table(header = TRUE, text = "
Scale ID m
1 1 1 0.4089795
2 1 1 0.001041055
3 1 1 0.1843616
4 1 1 0.03398921
5 1 1 FALSE
6 3 1 0.1179424
7 3 1 0.3569155
8 3 1 0.2006204
9 3 1 0.04024855
10 3 1 FALSE
")
谢谢你的帮助 df%
df <- read.table(header = TRUE, text = "
Scale ID m
1 1 1 0.4089795
2 1 1 0.001041055
3 1 1 0.1843616
4 1 1 0.03398921
5 1 1 FALSE
6 3 1 0.1179424
7 3 1 0.3569155
8 3 1 0.2006204
9 3 1 0.04024855
10 3 1 FALSE
")
library(tidyverse)
df %>%
group_by(Scale, ID) %>% # for each combination of Scale and ID
mutate(names = c("x","y","z","a","b")) %>% # add column names
ungroup() %>% # forget the grouping
spread(-Scale, -ID) %>% # reshape data
select(Scale, ID, x, y, z, a, b) # order columns
# # A tibble: 2 x 7
# Scale ID x y z a b
# <int> <int> <fct> <fct> <fct> <fct> <fct>
# 1 1 1 0.4089795 0.001041055 0.1843616 0.03398921 FALSE
# 2 3 1 0.1179424 0.3569155 0.2006204 0.04024855 FALSE
按(比例,ID)%>%对每个比例和ID组合进行分组
变异(名称=c(“x”、“y”、“z”、“a”、“b”))%>%#添加列名
取消分组()%>%#忘记分组
扩展(-Scale,-ID)%>%#重塑数据
选择(比例、ID、x、y、z、a、b)#顺序列
##A tibble:2 x 7
#刻度ID x y z a b
#
#1 1 0.4089795 0.001041055 0.1843616 0.03398921假
#2 3 1 0.1179424 0.3569155 0.2006204 0.04024855假
我的数据集的可能重复项没有列,列中的每个列的名称都要排列。我想将数据集分成五列,然后重命名它们。不过,如果这是不可能的,我会删除我的问题。
df <- read.table(header = TRUE, text = "
Scale ID m
1 1 1 0.4089795
2 1 1 0.001041055
3 1 1 0.1843616
4 1 1 0.03398921
5 1 1 FALSE
6 3 1 0.1179424
7 3 1 0.3569155
8 3 1 0.2006204
9 3 1 0.04024855
10 3 1 FALSE
")
library(tidyverse)
df %>%
group_by(Scale, ID) %>% # for each combination of Scale and ID
mutate(names = c("x","y","z","a","b")) %>% # add column names
ungroup() %>% # forget the grouping
spread(-Scale, -ID) %>% # reshape data
select(Scale, ID, x, y, z, a, b) # order columns
# # A tibble: 2 x 7
# Scale ID x y z a b
# <int> <int> <fct> <fct> <fct> <fct> <fct>
# 1 1 1 0.4089795 0.001041055 0.1843616 0.03398921 FALSE
# 2 3 1 0.1179424 0.3569155 0.2006204 0.04024855 FALSE