在 R 中编辑行和列

edit row and columns in R

我想这样做: 输入:

对于输出,我希望将 GTEX id 作为行,将 ENSG 作为列。 像这样:

SAMPLEID ENSGO ENSGO ENSGO
GTEX-1117F-022~ 0 187 0
GTEX-1117F-042~ 0 109 0

我尝试执行此命令,但它没有给我正确的输出:

GTEx_Analysis <- as.data.frame(t(GTEx_Analysis_2017_06_05_v8_RNASeQCv1_1_9_gene_reads))

带底座 R

df_new <- data.frame(t(df[,-c(1:2)]))
colnames(df_new) <- df$Name

tidyverse:

library(tidyverse)

  df_new <- df %>%
    select(-Description) %>%
    rowid_to_column() %>%
    pivot_longer(-c(Name, rowid)) %>%
    pivot_wider(names_from = c("Name", "rowid"), values_from = "value")

  colnames(df_new) <- str_replace_all(colnames(df_new), "\_[0-9]","")

输出

                ENSG0~ ENSG0~ ENSG0~
GTEX-1117F-022~      0    187      0
GTEX-1117F-042~      0    109      0

如果您需要保留 Description,另一种选择是在列标题中合并 NameDescription

library(tidyverse)
df %>%
  pivot_longer(-c(Name, Description)) %>%
  pivot_wider(names_from = c("Name", "Description"), values_from = "value")

  name            `ENSG0~_DDX11L1` `ENSG0~_WASH7p` `ENSG0~_MIR6859-1`
  <chr>                      <dbl>           <dbl>              <dbl>
1 GTEX-1117F-022~                0             187                  0
2 GTEX-1117F-042~                0             109                  0

数据

df <- structure(list(Name = c("ENSG0~", "ENSG0~", "ENSG0~"), Description = c("DDX11L1", 
"WASH7p", "MIR6859-1"), `GTEX-1117F-022~` = c(0, 187, 0), `GTEX-1117F-042~` = c(0, 
109, 0)), class = "data.frame", row.names = c(NA, -3L))