我的数据框(Annot_Subset)如下所示:
IlmnID UCSC_RefGene_Group
cg00050873 Body;TSS1500
cg00212031 TSS200
cg00213748
cg00214611 1stExon;5'UTR
cg00455876
cg01707559 TSS200;TSS200;TSS200
cg02004872 1stExon;5'UTR
我想做的是通过执行以下操作清理最后一栏:
用不同的字符串替换条目(例如Body; TSS1500),字符串为“Multiple_locations”
重复相同字符串重复的条目(例如TSS200; TSS200),该字符串出现一次
将字符串“Intergenic”添加到不包含任何内容的条目中。
举个例子:
IlmID UCSC_RefGene_Group
cg00050873 Multiple_locations
cg00212031 TSS200
cg00213748 Intergenic
cg00214611 Multiple_locations
cg00455876 Intergenic
cg01707559 TSS200
cg02004872 Multiple_locations
我写了一个能做到这一点的功能;但是想知道是否有更优雅和有效的方法来解决问题。特别是因为我的数据帧有485 000行。
这就是我的想法:
Gene_Group_Split<-strsplit(Annot_Subset$UCSC_RefGene_Group,";")
Clean.Gene.Group<-function(x) {
Gene_Group_Cleaned<-vector(mode="character",length=length(x))
for (i in 1:length(x)) {
if (length(x[[i]])>=1) {
unique_set<-unique(x[[i]])
if (length(unique_set)==1) {
Gene_Group_Cleaned[i]<-unique_set
} else {
Gene_Group_Cleaned[i]<-"Multiple_locations"
}
} else {
Gene_Group_Cleaned[i]<-"Intergenic"
}
}
return(Gene_Group_Cleaned)
}
Gene_Group_2<-Clean.Gene.Group(Gene_Group_Split)
答案 0 :(得分:2)
试试这个例子:
df <- read.table(text="
IlmnID UCSC_RefGene_Group
cg00050873 Body;TSS1500
cg00212031 TSS200
cg00213748
cg00214611 1stExon;5'UTR
cg00455876
cg01707559 TSS200;TSS200;TSS200
cg02004872 1stExon;5'UTR", fill=TRUE, header=TRUE, stringsAsFactors=FALSE)
df$Type <-
unlist(
lapply(df$UCSC_RefGene_Group, function(i){
x <- unique(unlist(strsplit(i,split = ";")))
ifelse(length(x)>1,"Multiple_locations",
ifelse(length(x)==0,"Intergenic",x))
})
)
#result
df
# IlmnID UCSC_RefGene_Group Type
# 1 cg00050873 Body;TSS1500 Multiple_locations
# 2 cg00212031 TSS200 TSS200
# 3 cg00213748 Intergenic
# 4 cg00214611 1stExon;5'UTR Multiple_locations
# 5 cg00455876 Intergenic
# 6 cg01707559 TSS200;TSS200;TSS200 TSS200
# 7 cg02004872 1stExon;5'UTR Multiple_locations
答案 1 :(得分:0)
library(dplyr)
library(stringi)
library(tidyr)
df = read.table(text="
IlmnID UCSC_RefGene_Group
cg00050873 Body;TSS1500
cg00212031 TSS200
cg00213748
cg00214611 1stExon;5'UTR
cg00455876
cg01707559 TSS200;TSS200;TSS200
cg02004872 1stExon;5'UTR", fill=TRUE, header=TRUE, stringsAsFactors=FALSE)
classify = function(string_vector)
if (length(string_vector) > 1) "Multiple_locations" else
if (string_vector == "") "Intergenic" else
string_vector
df %>%
mutate(UCSC_RefGene_Group =
UCSC_RefGene_Group %>%
stri_split_fixed(";")) %>%
unnest(UCSC_RefGene_Group) %>%
distinct %>%
group_by(IlmnID) %>%
summarize(class = classify(UCSC_RefGene_Group))