简体   繁体   English

如何迭代 R 中因子的水平?

[英]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.

相关问题 如何按R中的因子水平的预定顺序对数据帧进行排序? - How can I sort a dataframe by a predetermined order of factor levels in R? 我如何“seq_along”R中的因子水平? - How can I `seq_along` the levels of a factor in R? 如何按 R 中的多个日期过滤多个因子级别? - How can I filter multiple factor levels by multiple dates in R? 在因子水平上迭代 R function - Iterate R function over levels of a factor 如何使用 fct_relabel 但保持原始因子水平? 或者如何在 R 中设置具有部分字符串匹配的因子级别? - How can I use fct_relabel but maintain original factor levels? Or how can I set factor levels in R with partial string matches? 如何在 R 中完成一个变量在其因子水平上的相关性,按日期匹配 - How can I complete a correlation in R of one variable across it's factor levels, matching by date 如何将一个因子水平与R中的所有剩余水平进行比较 - How can I compare one level of a factor with all remaining levels in R 如何在 R 中的 dataframe 中创建具有三个级别的因子? - How do I create a factor with three levels in a dataframe in R? 如何在R中删除空间多边形数据框中的因子水平? - How do I delete factor levels in a spatialpolygonsdataframe in R? 如何将因子水平转换为 R 中的变量? - How do I convert factor levels to variables in R?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM