r-在r_中将数据集从一行移动到另一列



我有一个格式如下的数据集:

在此处输入图像描述

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包,但我没能成功完成这项简单的任务。我感谢你的帮助。我想要这样的东西:在此处输入图像描述

使用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   

基本R和一行:

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

最新更新