[英]How can I iterate the levels of a factor in R?
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 '''错误消息-c(can) 中的错误:一元运算符的参数无效
Observations If I do '''print(can)''' the output is "NULL" meaning that it is not working the use of "append".观察如果我执行 '''print(can)''' 输出为“NULL”,这意味着它不能使用“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),]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.