我有一个宽数据集,我想将其转换为长格式,并将列拆分为两组;在下面的总结示例中,变量得分n.1将是组1,变量得分n.2。如何将宽格式数据帧转换为长格式数据帧,并为各个变量分配一个组?
age.1<- c(23,34,52,12,23)
score1.1 <- c(44,23,62,1,0)
score2.1<- c(3,4,2,1,3)
score3.1<- c(230,304,502,102,203)
score1.2<- c(2343,4534,5652,1642,2233)
score1.2<- c(2233,32324,5232,1232,2233)
score2.2<- c(12323,12334,1352,1312,1323)
score3.2<- c(21233,33454,53452,12452,23532523)
df<- data.frame(age.1, score1.1,score2.1, score3.1, score1.2, score2.2, score3.2)
如果您想在旋转时将句点后的数字拆分为一个新列,那么我们可以使用names_pattern
:
library(tidyverse)
df %>% pivot_longer(
cols = -age.1,
names_to = c("name", "group"),
names_pattern = "(.+).(.)",
values_to = "Value"
)
输出
# A tibble: 30 × 4
age.1 name group Value
<dbl> <chr> <chr> <dbl>
1 23 score1 1 44
2 23 score2 1 3
3 23 score3 1 230
4 23 score1 2 2233
5 23 score2 2 12323
6 23 score3 2 21233
7 34 score1 1 23
8 34 score2 1 4
9 34 score3 1 304
10 34 score1 2 32324
# … with 20 more rows
然而,如果您需要在name
列中保留这些数字,那么我们可以在透视后获得值:
df %>%
pivot_longer(-age.1) %>%
mutate(group = str_replace(name, '.*\.', ""))
输出
# A tibble: 30 × 4
age.1 name value group
<dbl> <chr> <dbl> <chr>
1 23 score1.1 44 1
2 23 score2.1 3 1
3 23 score3.1 230 1
4 23 score1.2 2233 2
5 23 score2.2 12323 2
6 23 score3.2 21233 2
7 34 score1.1 23 1
8 34 score2.1 4 1
9 34 score3.1 304 1
10 34 score1.2 32324 2
# … with 20 more rows
我们可以使用stringi::stri_extract_last_regex
从字符串中提取最后一个数字:
library(dplyr)
library(tidyr)
df %>%
pivot_longer(-age.1) %>%
mutate(group = stringi::stri_extract_last_regex(name, "[0-9]+"))
# # A tibble: 30 × 4
# age.1 name value group
# <dbl> <chr> <dbl> <chr>
# 1 23 score1.1 44 1
# 2 23 score2.1 3 1
# 3 23 score3.1 230 1
# 4 23 score1.2 2233 2
# 5 23 score2.2 12323 2
# 6 23 score3.2 21233 2
# 7 34 score1.1 23 1
# 8 34 score2.1 4 1
# 9 34 score3.1 304 1
# 10 34 score1.2 32324 2
# # … with 20 more rows