-1

I have introduced some character values in mtcars dataset. The class of variables become character due to coercion.

My requirement is to get numeric values as numeric class and let the character values stay in their actual form i.e character class. So that i don't face a problem in doing calculations.

I tried as.numeric(as.character(data)) as well but it converts character values to NA.

I'm currently getting results for variables like 'abc' 'dcb' '4' '2' '6'.

But i need something like following: abc dcb 4 2 6

Can somebody please figure it out. I shall be extremely thankful.

My codes are as follows:

bb<-rep(x = 'abc', times=11)
cc<-rep(x = 'dcb', times=11)
mtcars[1,]<-bb
mtcars[2,]<-cc
Doctor
  • 59
  • 1
  • 11
  • 3
    You can store it in a `list` as it can have different type. A `vector` can have only a single type. If there is a single character element, it gets converted to that type. So, perhaps `l1 <- list(c(1, 2, 6), "apple")` – akrun Jan 21 '19 at 10:30
  • Thanks. What if i got a data set (e.g mtcars) with first three rows as characters and remaining rows in numeric form? This is my more related to my actual problem – Doctor Jan 21 '19 at 10:38
  • I have updated my codes. pls have a look. Thanks :) – Doctor Jan 21 '19 at 11:06

1 Answers1

0

As list stores multiple types, if u check for numeric and get the values of the vector as numeric.

list_data = sapply(data,function(x) {if(is.numeric(x))as.numeric(x)})
JineshEP
  • 738
  • 4
  • 7
  • Thanks. What if i got a data set (e.g mtcars) with first three rows as characters and remaining rows in numeric form? This is my more related to my actual problem – Doctor Jan 21 '19 at 10:44
  • is.numeric(x) will be false for any string or character, you'd need to make something more like if(is.numeric(as.numeric(as.character(x)))){x}else{as.character(x)} but you'd still get an NA warning – Phi Jan 21 '19 at 10:54
  • !is.na(as.numeric(x)) would do – JineshEP Jan 21 '19 at 10:58
  • I dont think u can have a vector that has few elements as char and few number, use a list instead as suggested. – JineshEP Jan 21 '19 at 11:09
  • !is.na(as.numeric(x)) it removes the character value, i want the character value to stay as it is – Doctor Jan 21 '19 at 11:13
  • The list function doesn't work on updated mtcars data – Doctor Jan 21 '19 at 11:16