我在一个 xlsx 文件中有数千行,我想删除所有超过 5 个句点的行(每行是数字、字母和句点的组合)。
我在 Excel 中的 3 行示例:
2a02.587.e815.cb8d.35bf.5c99.8d51.417b
2a02.587.e815.727
3a03.5c99.8d51.417b.5212e
我使用了以下代码,但它返回错误:
library(tidyverse)
df1 %>%
filter(str_count("[.]") >=5)
您可以用同样的方式修改您的解决方案。在这里,我首先用两个反斜杠转义 .
以指定对文字 .
的引用:
library(stringr)
df1 %>%
filter(str_count(str,"\\.") <= 5)
# A tibble: 2 x 1
str
<chr>
1 2a02.587.e815.727
2 3a03.5c99.8d51.417b.5212e
数据
structure(list(str = c("2a02.587.e815.cb8d.35bf.5c99.8d51.417b","2a02.587.e815.727","3a03.5c99.8d51.417b.5212e")),row.names = c(NA,-3L),class = c("tbl_df","tbl","data.frame"))
,
使用 gsub
+ nchar
试试下面的代码,这会删除除 .
之外的所有字符:
df %>%
filter(nchar(gsub("[^.]","",V1))<=5)
它给了
V1
1 2a02.587.e815.727
2 3a03.5c99.8d51.417b.5212e
#数据
> dput(df)
structure(list(V1 = c("2a02.587.e815.cb8d.35bf.5c99.8d51.417b",class = "data.frame",-3L))