如何根据R中列中的特定字符串重塑或转置 Dataframe ?[重复]

dced5bon  于 2023-04-18  发布在  其他
关注(0)|答案(1)|浏览(113)

此问题已在此处有答案

How to reshape data from long to wide format(14个答案)
7天前关闭
我有一个这样的数据框

test <- data.frame(matrix(nrow = 18, ncol = 3))
colnames(test) <- c("subject","session","f1")
test$subject <- c(1,1,1,2,2,2,3,3,3,1,1,1,2,2,2,3,3,3)
test$session <- c(1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2)
test$f1 <-      c(29,52,72,42,50,52,30,49,63,51,37,43,1,3,2,1,2,0)

我希望它看起来像这样

test <- data.frame(matrix(nrow=6,ncol = 5))
colnames(test) <- c("subject","session","t1","t2","t3")
test$subject <- c(1,2,3,1,2,3)
test$session <- c(1,1,1,2,2,2)
test$t1 <- c(29,42,30,51,1,1)
test$t2 <- c(52,50,49,37,3,2)
test$t3 <- c(72,52,63,43,2,0)

我该怎么去改变它?

5ktev3wc

5ktev3wc1#

我们可以只使用pivot_wider()names_prefix()参数:正如@Martin Gal在没有unnest的情况下提出的:

library(tidyr)
library(dplyr)

test %>% 
  mutate(rn = row_number(), .by = c(subject, session)) %>% 
  pivot_wider(names_from = "rn", 
              values_from = "f1",  
              names_prefix = "t_")
library(tidyr)
library(dplyr)

test %>%
  mutate(row = row_number(), .by = c(subject, session)) %>% 
  pivot_wider(names_from = row, values_from = f1, 
              names_prefix = "t", names_sort = TRUE, 
              values_fn = list) %>% 
  unnest(cols = starts_with("t"))

  subject session t1 t2 t3
1       1       1 29 52 72
2       2       1 42 50 52
3       3       1 30 49 63
4       1       2 51 37 43
5       2       2  1  3  2
6       3       2  1  2  0

相关问题