原始數(shù)據(jù)是這樣的
GO_test.png
我要轉(zhuǎn)換成如下的格式
gene_GO_ID.png
只會(huì)的一條路轉(zhuǎn)
## 借用一個(gè)例子 https://zhuanlan.zhihu.com/p/27792447
rm(list = ls())
GO_test <- read.table(file.choose(),sep = "\t" ,header = F)
# GO_test <- read.table(”1.txt“,sep = "\t" ,header = F)
> 1、 得到包含list中個(gè)數(shù)的數(shù)據(jù)框
## 添加第二列中每一行所含有的個(gè)數(shù)
GO_list <- strsplit(as.vector(GO_test$V2)," ") ## 將第二列的字符串按空格切割變成list
length(GO_list[[1]]) ## 查看第一個(gè)list中的個(gè)數(shù)
GO_length <- c() ## 創(chuàng)建一個(gè)空的向量
for (i in 1:length(GO_list)) {
GO_length[i] <- length(GO_list[[i]])
} ## 計(jì)算出每一個(gè)list的長(zhǎng)度
GO_test$length <- GO_length ## 將長(zhǎng)度添加到GO_test表中
> 2、
times <- as.numeric(GO_test$length)
gene_ID <- rep( as.vector(GO_test[,1]),times) #得到gene ID
GO_ID<- data.frame(matrix(unlist(GO_list), byrow=T),stringsAsFactors=FALSE) ##得到GO號(hào)
data.frame(gene_ID = gene_ID,GO_ID = GO_ID) -> gene_GO_ID # 合并
> 3灸叼、
colnames(gene_GO_ID) <- c("gene_ID","GO_ID")
在看完 《 R for data science》后的方法記錄中鼠,來(lái)源于`章節(jié) 19``
#### 生物信息學(xué)應(yīng)用:
- 巧用 `stringr::str_split()` 和 `unnest()` 函數(shù)將 GO 背景文件分瘦,將一列拆分成多行
- 巧用 `tidyr::separate_rows()` 函數(shù)將一列拆分成多行
```{r}
test <- tribble(
~gene, ~GO_ID,
"gene1", paste0("GO:1", ";", "GO:2", ";","GO:3")
)
> test
# A tibble: 1 x 2
gene GO_ID
<chr> <chr>
1 gene1 GO:1;GO:2;GO:3
test %>%
mutate(Go_id = stringr::str_split(GO_ID, ";")) %>%
unnest() %>%
select(gene, Go_id)
# A tibble: 3 x 2
gene Go_id
<chr> <chr>
1 gene1 GO:1
2 gene1 GO:2
3 gene1 GO:3
第三種
test <- tribble(
~gene, ~GO_ID,
"gene1", paste0("GO:1", ";", "GO:2", ";","GO:3")
)
test %>%
tidyr::separate_rows(GO_ID, sep = ";")
``