处理矩阵或者数据框时,有时会对计算每行或每列中某些数值或某一个或几个字符的个数。当该数字或字符出现一定次数后选择保留或舍弃当前行的数据。
翻了半天Google终于找到两种解决方案。如下:
-
> m <- matrix(c("a","b","c","b","b","c","c","c","a","c","c","b"), ncol=3)
-
> m
-
[,1] [,2] [,3]
-
[1,] "a" "b" "a"
-
[2,] "b" "c" "c"
-
[3,] "c" "c" "c"
-
[4,] "b" "c" "b"
-
> m[rowSums(m=="b"|m=="a")>1,] # 方法1
-
[,1] [,2] [,3]
-
[1,] "a" "b" "a"
-
[2,] "b" "c" "b"
-
> m[apply(m=="b",1,sum)>1,] #方法2
-
[1] "b" "c" "b"
-
> m[rowSums(m=="b"|m=="a")==2,]
-
[1] "b" "c" "b"
阅读(888) | 评论(0) | 转发(0) |