Reputation: 740
Is there a simple way to remove all non numeric values from a vector in r? Suppose we have:
vec <- c(1, 2, T, 'x', 'abc', '6', 7, F, F, 10)
I would like to receive:
c(1, 2, 7, 10)
Upvotes: 0
Views: 4134
Reputation: 670
c
is a function that returns a vector where "all arguments are coerced to a common type...The output type is determined from the highest type of the components in the hierarchy NULL < raw < logical < integer < double < complex < character < list < expression."
Thus, you need a container where you can have mixed data types to test which ones are numeric. A list
gives you this. This approach leaves out the '6'
:
vec_list <- list(1, 2, T, 'x', 'abc', '6', 7, F, F, 10)
unlist(vec_list[sapply(vec_list, function(x) if(class(x)=='numeric') {T} else {F})])
[1] 1 2 7 10
Upvotes: 2
Reputation: 101733
A simple solution is to use Filter
over vec <- list(1, 2, T, 'x', 'abc', '6', 7, F, F, 10)
, i.e.,
> unlist(Filter(is.numeric,vec))
[1] 1 2 7 10
Upvotes: 1
Reputation: 263362
Techically the term vector includes lists that do not have attributes other than names, so here is a vector built with list
rather than with c
.
vec <- list(1, 2, T, 'x', 'abc', '6', 7, F, F, 10)
So that can be tested for "numericy"
vec[sapply(vec, is.numeric)]
[[1]]
[1] 1
[[2]]
[1] 2
[[3]]
[1] 7
[[4]]
[1] 10
Upvotes: 0
Reputation: 1231
You can use regex to look for elements that only contain the digits 0-9 along with periods and return them. The ^
matches the start of a character and $
matches the end so it will filter out any element which has both letters and numbers.
as.numeric(grep('^-?[0-9.]+$', vec, val = T))
Upvotes: 2