Keep only numeric in specific column in R?

Viewed 546

df

X1 X2 X3 X4 X5
1 1 11 21 a k
j 2 12 22 b l
3 3 13 23 c m
t 4 14 24 d n
5 5 15 25 e o
k 6 16 26 f p
7 7 17 27 g q
z 8 18 28 h r
9 9 19 29 i s
10 10 20 30 j 

I have a dataframe which contains 5 columns and 10 rows. I want for only column 1 (X1) to keep only the numeric form and remove any characters eg character "j" in column X1, row 2. Might anyone know how to do this using a script in R?

The final outcome would ideally look like this

   X1 X2 X3 X4 X5
1   1 11 21  a  k
3   3 13 23  c  m
5   5 15 25  e  o
7   7 17 27  g  q
9   9 19 29  i  s
10 10 20 30  j 
1 Answers

If you convert the column to numeric, any values that can't be converted will become NA - which you can then drop.

# in base R
df$X1 = as.numeric(df$X1)
df = df[!is.na(df$X1), ]

# same thing with dplyr
library(dplyr)
df = df %>%
  mutate(X1 = as.numeric(X1)) %>%
  filter(!is.na(X1))
Related