简体   繁体   English

根据条件删除R中的矩阵行

[英]Remove rows of a Matrix in R according to a condition

Imagine you have the following matrix in R: 假设您在R中具有以下矩阵:

      [,1]   [,2] [,3] [,4] [,5]
[1,]  "A/B"    3    4    5    7
[2,]  "A/C"    8    6    7    7
[3,]  "A/B/C"  8    8    5    4

What is the easiest way to remove the rows where I have more than two letters on the first column? 删除第一列中两个以上字母的行的最简单方法是什么? I think the rationale should be something like: 我认为基本原理应类似于:

if nchar(matrix[,1]!=3) then remove that row

But I don't know how to code this. 但是我不知道该怎么编码。 Any help would be appreciated! 任何帮助,将不胜感激! Thanks 谢谢

Convert your matrix to a data frame, and then use grepl to check for a matching pattern of three or more letter: 将矩阵转换为数据框,然后使用grepl检查三个或更多字母的匹配模式:

df <- df[!grepl("\\w/\\w/\\w.*", df$letters),]

在此处输入图片说明

Demo 演示

Some of the suggestions in the comments above might also work for you, but a regex based solution has the added benefit that it is robust, and can be easily changed if your requirements change at some point in the future. 上面的注释中的一些建议也可能对您有用,但是基于正则表达式的解决方案还具有健壮的附加优点,并且如果将来您的需求发生变化,可以轻松更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM