Drop Data Frame Rows with Non-Numeric Characters in Column in R (Example Code)
This tutorial shows how to remove data frame rows with non-numeric characters in a particular column in the R programming language.
Introduction of Example Data
df <- data.frame(col1 = c(letters[1:3], # Constructing example data 1:2, letters[1:3]), col2 = 1:8, col3 = 8:1) df # col1 col2 col3 # 1 a 1 8 # 2 b 2 7 # 3 c 3 6 # 4 1 4 5 # 5 2 5 4 # 6 a 6 3 # 7 b 7 2 # 8 c 8 1 |
df <- data.frame(col1 = c(letters[1:3], # Constructing example data 1:2, letters[1:3]), col2 = 1:8, col3 = 8:1) df # col1 col2 col3 # 1 a 1 8 # 2 b 2 7 # 3 c 3 6 # 4 1 4 5 # 5 2 5 4 # 6 a 6 3 # 7 b 7 2 # 8 c 8 1
Example: Apply as.numeric() & is.na() Functions to Keep Only Rows Containing Characters
df_subset <- df[!is.na(as.numeric(df$col1)), ] # Remove numeric rows df_subset # col1 col2 col3 # 4 1 4 5 # 5 2 5 4 |
df_subset <- df[!is.na(as.numeric(df$col1)), ] # Remove numeric rows df_subset # col1 col2 col3 # 4 1 4 5 # 5 2 5 4