0

I have a data frame (let's call it 'df') it consists of two columns

 Name   Contact
 A      34552325
 B      423424
 C      4324234242
 D      hello1@company.com

I want to split the dataframe into two dataframe based on whether a row in column "Contact" is numeric or not

Expected Output:

 Name   Contact
 A      34552325
 B      423424
 C      4324234242

and

 Name   Contact
 D      hello1@company.com

I tired using:

   df$IsNum <- !(is.na(as.numeric(df$Contact))) 

But this classified "hello1@company.com" also as numeric.

Basically if there is even a single non-numeric value in column "Contact", then code must classify it as non-numeric

David Arenburg
  • 91,361
  • 17
  • 137
  • 196
Anubhav Dikshit
  • 1,729
  • 6
  • 25
  • 48
  • You probably have factors there, so just `as.numeric` won't work, Try `split(df, is.na(as.numeric(as.character(df$Contact))))` maybe – David Arenburg Oct 27 '15 at 10:15
  • for me worked your approach, after I did `df$Contact <- as.vector(df$Contact)`. I also did like this `df$IsNum <- suppressWarnings({!(is.na(as.numeric(df$Contact)))})` in order to get rid of the `warning message` – Paul Oct 27 '15 at 10:23

2 Answers2

2

You may use grepl..

x <- " Name   Contact
 A      34552325
 B      423424
 C      4324234242
 D      hello1@company.com"
df <- read.table(text=x, header = T)
x <- df[grepl("^\\d+$",df$Contact),]
y <- df[!grepl("^\\d+$",df$Contact),]
x
#   Name    Contact
# 1    A   34552325
# 2    B     423424
# 3    C 4324234242
y
#  Name            Contact
# 4    D hello1@company.com
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
1

We can create a grouping variable with grepl (same as how @Avinash Raj created), split the dataframe with that to create a list of data.frames.

split(df, grepl('^\\d+$', df$Contact))
akrun
  • 874,273
  • 37
  • 540
  • 662