Search code examples
rlapplynumeric

Getting a vector of all unique numerical values in a data.frame


I have data as follows:

dat <- structure(list(rn = c("region", "lower threshold", "upper threshold"
), east_0_25 = c("east", "0", "25"), north_0_25 = c("north", 
"0", "25")), row.names = c(NA, -3L), class = c("data.table", 
"data.frame"))

                rn east_0_25 north_0_25
1:          region      east      north
2: lower threshold         0          0
3: upper threshold        25         25

I am wondering what the easiest way would be to create a vector of all unique numerical values out of this data.frame, noting that 0 and 25 are character values.

I guess I could start with:

dat <- lapply(dat, as.numeric)

To keep only the numerical values. But what should be the next step?

Desired outcome:

unique_num_values <- c(0,25)

Solution

  • You can use the following code:

    x <- unique(as.numeric(unlist(dat)))
    unique_num_values <- x[!is.na(x)]
    

    Output:

    [1]  0 25