问题
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