将数据框中特定列转置

5

如何将数据框中的特定列进行转置:

id<- c(1,2,3)
t0<- c(0,0,0)
bp0<- c(88,95,79)
t1<- c(15,12,12)
bp1<- c(92,110,82)
t2<- c(25,30,20)
bp2<- c(75,99,88)

df1<- data.frame(id, t0, bp0, t1, bp1, t2, bp2)
df1

> df1
  id t0 bp0 t1 bp1 t2 bp2
1  1  0  88 15  92 25  75
2  2  0  95 12 110 30  99
3  3  0  79 12  82 20  88

In order to obtain: 

> df2
  id  t  bp
1  1  0  88
2  2  0  95
3  3  0  79
4  1 15  92
5  2 12 110
6  3 12  82
7  1 25  75
8  2 30  99
9  3 20  88


为了获取与“id”对应的t(t0,t1,t2)和bp(bp0,bp1,bp2),以获取df2。
3个回答

4

使用Base R,您可以做到:

Reprex

  • 编写代码
df2 <- cbind(df1[1], stack(df1, startsWith(names(df1), "t"))[1], stack(df1,startsWith(names(df1), "bp"))[1])

names(df2)[2:3] <- c("t", "bp")
  • 输出
df2
#>   id  t  bp
#> 1  1  0  88
#> 2  2  0  95
#> 3  3  0  79
#> 4  1 15  92
#> 5  2 12 110
#> 6  3 12  82
#> 7  1 25  75
#> 8  2 30  99
#> 9  3 20  88

此示例代码于2022年2月14日使用reprex包 (v2.0.1)创建


1
谢谢,它很好用。对我来说,在答案中是更简单的形式。 - Miguel Angel Arnau

3

以下是使用 pivot_longername_pattern 的解决方案:

\\w+ = 一个或多个字母字符

\\d+ = 一个或多个数字

library(dplyr)
library(tidyr)

df1 %>% 
  pivot_longer (
    -id,
    names_to = c(".value", "name"), 
    names_pattern = "(\\w+)(\\d+)"
  ) %>% 
  select(-name)

      id     t    bp
  <dbl> <dbl> <dbl>
1     1     0    88
2     1    15    92
3     1    25    75
4     2     0    95
5     2    12   110
6     2    30    99
7     3     0    79
8     3    12    82
9     3    20    88

2

使用 reshape 的基本 R 选项

reshape(
  setNames(df1, sub("(\\d+)", ".\\1", names(df1))),
  direction = "long",
  idvar = "id",
  varying = -1
)

提供

    id time  t  bp
1.0  1    0  0  88
2.0  2    0  0  95
3.0  3    0  0  79
1.1  1    1 15  92
2.1  2    1 12 110
3.1  3    1 12  82
1.2  1    2 25  75
2.2  2    2 30  99
3.2  3    2 20  88

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接