英文:
How to reshape or transpose a data frame based off specific strings in columns in R?
问题
I have a data frame like this
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)
I would like it to look like this
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)
How would I go about changing it?
英文:
I have a data frame like this
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)
I would like it to look like this
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)
How would I go about changing it?
答案1
得分: 2
以下是您要翻译的内容:
We could use just pivot_wider()
with names_prefix()
argument:
as proposed by @Martin Gal without 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
英文:
We could use just pivot_wider()
with names_prefix()
argument:
as proposed by @Martin Gal without 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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论