R: Deleting elements from a vector based on element length

我只是一个虾纸丫 提交于 2019-12-21 21:29:39

问题


How can I delete elements from a vector of strings depending on the number of characters or length of the strings?

df <- c("asdf","fweafewwf","af","","","aewfawefwef","awefWEfawefawef")
> df
[1] "asdf"            "fweafewwf"       "af"              ""                ""                "aewfawefwef"     "awefWEfawefawef"

For example, I may want to delete all elements of df with a length smaller than 5, so the output would be:

> df
[1]"fweafewwf"        "aewfawefwef"     "awefWEfawefawef"

Thanks!


回答1:


Just use nchar:

> df[nchar(df) > 5]
[1] "fweafewwf"       "aewfawefwef"     "awefWEfawefawef"



回答2:


Since nchar works weird with NA's:

nchar(NA)
## [1] 2

I recommend to use stri_length function from stringi package

require(stringi)
df[stri_length(df)>5]


来源:https://stackoverflow.com/questions/23142482/r-deleting-elements-from-a-vector-based-on-element-length

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!