r - Remove NA strings from table (characters) in R
问题描述
How can I remove NA strings in a simple data frame like the one below, which consists of a single column, in R?
head(test)
Column1
[1] "Gene1 Gene2 Gene3 NA NA NA NA"
[2] "Gene41 NAGene218 GeneX NA"
[3] "Gene19 GeneNA NA NA NA NA NA"
Some genes start or end with 'NA', so to avoid getting rid of those NAs, the gsub regex has to specify the position of the NA in the string... Something like:
test2 <- gsub('^ NA$', "", test$Column1)
, with ^
indicating that ' NA' has to be at the start and $
at the end of the string... I am sure it's something simple, but I don't understand what I am doing wrong? (As I am not very familiar with these regex symbols)
[UPDATE] - Desired output
head(test2)
Column1
[1] "Gene1 Gene2 Gene3"
[2] "Gene41 NAGene218 GeneX"
[3] "Gene19 GeneNA"
解决方案
您可以使用
test$Column1 <- gsub("^NA(?:\\s+NA)*\\b\\s*|\\s*\\bNA(?:\\s+NA)*$", "", test$Column1)
查看正则表达式演示
细节
^NA(?:\s+NA)*\b\s*
- 备选方案 1:^
- 字符串的开始NA
-NA
字符串(?:\s+NA)*
- 0 次或多次重复 1+ 空格和NA
文本\b
- 确保有一个单词边界(不NAGene
应该发生匹配)\s*
- 0+ 个空格
|
- 或者\s*\bNA(?:\s+NA)*$
- 备选方案 2:\s*
- 0+ 个空格\b
- 确保有一个单词边界(不GeneNA
应该发生匹配)NA
-NA
字符串(?:\s+NA)*
- 0 次或多次重复 1+ 空格和NA
文本$
- 字符串结束。
推荐阅读
- sql - 尝试在 SQL Server 中重写 Access 查询
- css - 如何将 div 放在屏幕两侧而不是页面内容的其余部分?
- react-native - JavaScriptCore/React-Native 的 C-FFI
- swift - UIBarButtonItem 太宽
- java - 尝试使用 junit5 和 mockito 模拟 byte[] 值时为空值
- python - 使用下拉菜单创建虚线图
- python - Tkinter - 如果使用网格满足用户输入,如何更改标签背景的颜色
- javascript - JSDoc 注释未显示在绝对路径导入上
- typescript - '{ [index: string]: string; 类型的转换 }' 输入 'T' 可能是一个错误,因为这两种类型都没有与另一种充分重叠
- python - 是否有一个函数可以告诉 Keras 模型在分类时省略图片的某些部分?