I would like to create a function that helps me to identify possible mistakes in the levels of a factor by accessing the first letter, so first I am focused on the identification part.
Data Frame '''
alleles<-(c('A*24:02', 'A*11:01', 'blank', 'A*31:01'))
as.factor(alleles)
freq<-c(0.3782, 0.4209, 0.0362, 0.0761)
df<-data.frame(alleles, freq)
'''
My attempt _ '''
for(i in df$alleles){
if (i != 'A'){
can<-c()
append(can, i)
df$alleles<-df$alleles[-c(can)]
}
}
''' Error message Error in -c(can) : invalid argument to unary operator
Observations If I do '''print(can)''' the output is "NULL" meaning that it is not working the use of "append".
You can also try:
#Data
alleles<-(c('A*24:02', 'A*11:01', 'blank', 'A*31:01'))
freq<-c(0.3782, 0.4209, 0.0362, 0.0761)
df<-data.frame(alleles, freq)
can<-c()
#Check
for(i in 1:length(df$alleles))
{
if (substr(df$alleles[i],1,1) != 'A'){
can <- c(can, as.character(df$alleles[i]))
}
}
#Apply
df<-df[-which(df$alleles %in% can),]
Output:
df
alleles freq
1 A*24:02 0.3782
2 A*11:01 0.4209
4 A*31:01 0.0761
为什么不直接使用正则表达式?
df[grepl("^A", df$alleles),]
我们可以使用grep
df[grep("^A", df$alleles),]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.