M. Rasyid Ridha M. Rasyid Ridha - 2 months ago 7
R Question

Filter list in R which has nchar > 1

I have a list of names

> x <- c("Test t", "Cuma Nama K", "O", "Test satu dua t")
> name <- strsplit(x, " ")
> name
[[1]]
[1] "Test" "t"

[[2]]
[1] "Cuma" "Nama" "K"

[[3]]
[1] "O"

[[4]]
[1] "Test" "satu" "dua" "t"


How can I filter a list so that it can become like this?
I am trying to find out how to filter the list which has nchar > 1

> name
[[1]]
[1] "Test"

[[2]]
[1] "Cuma" "Nama"

[[4]]
[1] "Test" "satu" "dua"

Answer
lapply(name, function(x) x[nchar(x)>1])

Results in:

[[1]]
[1] "Test"

[[2]]
[1] "Cuma" "Nama"

[[3]]
character(0)

[[4]]
[1] "Test" "satu" "dua"