I have the following data:
structure(list(Tempo = c("t0", "t1", "REC1", "REC2", "REC4",
"REC8", "REC11"), sig_C = c("a", "a", "a", "a", "a", "a", "a"
), sig_C1 = c("a", "a", "a", "a", "a", "a", "a"), sig_C2 = c("a",
"a", "a", "a", "a", "a", "a"), sig_C3 = c("a", "a", "a", "a",
"a", "a", "a"), sig_C4 = c("a", "a", "a", "a", "a", "a", "a"),
sig_C5 = c("a", "b", "b", "ab", "ab", "ab", "a")), row.names = c(NA,
-7L), class = c("tbl_df", "tbl", "data.frame"))
I would to like transpose this data frame, keeping Tempo
as column names and sig_C untill sig_C5 as a variable called group.
I try to use t()
function, but not work in the desired way.
Thanks
CodePudding user response:
Perhaps something like this to touch up t()
result:
library(dplyr)
library(tibble)
dft <- t(df)
colnames(dft) <- dft[1,]
as.data.frame.matrix(dft[-1,]) %>%
rownames_to_column("Group") %>%
as_tibble()
#> # A tibble: 6 × 8
#> Group t0 t1 REC1 REC2 REC4 REC8 REC11
#> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr>
#> 1 sig_C a a a a a a a
#> 2 sig_C1 a a a a a a a
#> 3 sig_C2 a a a a a a a
#> 4 sig_C3 a a a a a a a
#> 5 sig_C4 a a a a a a a
#> 6 sig_C5 a b b ab ab ab a
Input:
df <- structure(list(
Tempo = c(
"t0", "t1", "REC1", "REC2", "REC4",
"REC8", "REC11"
), sig_C = c("a", "a", "a", "a", "a", "a", "a"), sig_C1 = c("a", "a", "a", "a", "a", "a", "a"), sig_C2 = c(
"a",
"a", "a", "a", "a", "a", "a"
), sig_C3 = c(
"a", "a", "a", "a",
"a", "a", "a"
), sig_C4 = c("a", "a", "a", "a", "a", "a", "a"),
sig_C5 = c("a", "b", "b", "ab", "ab", "ab", "a")
), row.names = c(
NA,
-7L
), class = c("tbl_df", "tbl", "data.frame"))
Created on 2023-01-26 with reprex v2.0.2
CodePudding user response:
You could try using pivot()
from the tidyr
library to reshape it.
library(tidyr)
df_reshaped <- pivot(data = df, id_cols = Tempo, cols_to_rename = sig_C:sig_C5, values_to = "group")
After running this, you'll have the dataframe with Tempo as columns and sig_C to sig_C5 as variable called group.