在 R 中重塑数据集_将行移动到列
Reshape dataset in R_ move row to column
我有一个格式如下的数据集:
enter image description here
structure(list(SNPID = c("SNP_A-1780520", "SNP_A-1780618", "SNP_A-1780632"
), no.1 = c("BB", "AB", "AA"), no.2 = c("BB", "AB", "AA"), no.3 = c("BB",
"AB", "AB")), row.names = c(NA, -3L), class = c("tbl_df", "tbl",
"data.frame"))`
我想重塑数据集,将每个 SNPID 作为一列,将每个“否”作为一行。
我尝试过不同的 R 包,但未能成功完成这个简单的任务。我感谢任何帮助。我想要这样的东西:
enter image description here
使用 tidyr()
重塑数据的示例
library (tidyr)
df %>%
pivot_longer(-SNPID) %>%
pivot_wider(names_from = SNPID, values_from = value)
name `SNP_A-1780520` `SNP_A-1780618` `SNP_A-1780632` `SNP_A-1780654`
<chr> <chr> <chr> <chr> <chr>
1 no.1 BB AB AA AA
2 no.2 BB AB AA AA
3 no.3 BB AB AA AA
Base R 和 oneliner:
df = structure(list(SNPID = c("SNP_A-1780520", "SNP_A-1780618", "SNP_A-1780632" ), no.1 = c("BB", "AB", "AA"), no.2 = c("BB", "AB", "AA"), no.3 = c("BB", "AB", "AB")), row.names = c(NA, -3L), class = c("tbl_df", "tbl", "data.frame"))
df_new = as.data.frame(t(df))
输出:
df_new
V1 V2 V3
SNPID SNP_A-1780520 SNP_A-1780618 SNP_A-1780632
no.1 BB AB AA
no.2 BB AB AA
no.3 BB AB AB
这就是 data.table::transpose
的情况
data.table::transpose(df1, make.names = "SNPID", keep.names = "name")
name SNP_A-1780520 SNP_A-1780618 SNP_A-1780632
1 no.1 BB AB AA
2 no.2 BB AB AA
3 no.3 BB AB AB
我有一个格式如下的数据集:
enter image description here
structure(list(SNPID = c("SNP_A-1780520", "SNP_A-1780618", "SNP_A-1780632"
), no.1 = c("BB", "AB", "AA"), no.2 = c("BB", "AB", "AA"), no.3 = c("BB",
"AB", "AB")), row.names = c(NA, -3L), class = c("tbl_df", "tbl",
"data.frame"))`
我想重塑数据集,将每个 SNPID 作为一列,将每个“否”作为一行。
我尝试过不同的 R 包,但未能成功完成这个简单的任务。我感谢任何帮助。我想要这样的东西: enter image description here
使用 tidyr()
重塑数据的示例library (tidyr)
df %>%
pivot_longer(-SNPID) %>%
pivot_wider(names_from = SNPID, values_from = value)
name `SNP_A-1780520` `SNP_A-1780618` `SNP_A-1780632` `SNP_A-1780654`
<chr> <chr> <chr> <chr> <chr>
1 no.1 BB AB AA AA
2 no.2 BB AB AA AA
3 no.3 BB AB AA AA
Base R 和 oneliner:
df = structure(list(SNPID = c("SNP_A-1780520", "SNP_A-1780618", "SNP_A-1780632" ), no.1 = c("BB", "AB", "AA"), no.2 = c("BB", "AB", "AA"), no.3 = c("BB", "AB", "AB")), row.names = c(NA, -3L), class = c("tbl_df", "tbl", "data.frame"))
df_new = as.data.frame(t(df))
输出:
df_new
V1 V2 V3
SNPID SNP_A-1780520 SNP_A-1780618 SNP_A-1780632
no.1 BB AB AA
no.2 BB AB AA
no.3 BB AB AB
这就是 data.table::transpose
data.table::transpose(df1, make.names = "SNPID", keep.names = "name")
name SNP_A-1780520 SNP_A-1780618 SNP_A-1780632
1 no.1 BB AB AA
2 no.2 BB AB AA
3 no.3 BB AB AB