2

I have here a small list of strings:

> dput(test)
list(c("jason", "mid1920s", "living2018"))

I want to remove words with numbers so that the list only contains "jason". I've tried this code to no avail. (I would like a solution to apply my function in a list, not a vector or dataframe)

test[[1]] <- lapply(test[[1]], gsub("[[:digit:]]+", "", .))

1 Answers1

2

Regarding the use of lapply in the OP's code and the list is of length 1. In that case, it could be extracted and apply the gsub

test[[1]] <- gsub("\\d+", "", test[[1]]

Also, in the OP's code there is a . which is incorrect

lapply(test[[1]], gsub("[[:digit:]]+", "", .))

It should be

lapply(test, function(x) gsub("[[:digit:]]+", "", x))

But, if the intention is to filter out the elements that have a number, then grep would be useful as gsub removes the substring i.e. one or more digits (\\d+) from the string.

test[[1]] <- test[[1]][!grepl("\\d+", test[[1]])]

In addition, if there are many list elements, we can use lapply

lapply(test, function(x) x[!grepl("\\d+", x)])
akrun
  • 874,273
  • 37
  • 540
  • 662