-1

I have a very simple question, but I cannot find the answer: I have this data.frame:

b=c("a","a","a","a","a","b","b","b","b","c")
c=c("b","b","b","b","b","c","c","c","c","d")

a<-data.frame(b,c)

Why if I'd like to put in one column the a$b and a$c vector with this:

f<-c(a$b,a$c)

The result is not like

> f<-c(b,c)
> f
 [1] "a" "a" "a" "a" "a" "b" "b" "b" "b" "c" "b" "b" "b" "b" "b" "c" "c" "c" "c" "d"

but

> f<-c(a$b,a$c)
> f
 [1] 1 1 1 1 1 2 2 2 2 3 1 1 1 1 1 2 2 2 2 3

? Thanks in advance!

EDIT: Tried this, looking at the possible duplicate suggest above:

> a<-data.frame(z=as.character(b),k=as.character(c))
> f<-c(a$z,a$k)
> f  [1] 1 1 1 1 1 2 2 2 2 3 1 1 1 1 1 2 2 2 2 3
s__
  • 9,270
  • 3
  • 27
  • 45
  • Possible duplicate of [Convert data.frame columns from factors to characters](http://stackoverflow.com/questions/2851015/convert-data-frame-columns-from-factors-to-characters) – Ronak Shah Nov 08 '16 at 11:39
  • Hi, if I am not wrong that does not work, but the solution under yes! – s__ Nov 08 '16 at 12:04
  • Basically, this is a very common problem where we consider factor as characters and try to do different operations on them. It would also work if you do `f <- c(as.character(a$z), as.character(a$k))` – Ronak Shah Nov 08 '16 at 12:14

1 Answers1

2

You have to set stringsAsFactors to FALSE in the data.frame() function. Otherwise the strings are interpreted as factors, resulting in your undesired output.

b <- c("a","a","a","a","a","b","b","b","b","c")
c <- c("b","b","b","b","b","c","c","c","c","d")

a <- data.frame(b,c, stringsAsFactors = F)

f <- c(a$b,a$c)

f
[1] "a" "a" "a" "a" "a" "b" "b" "b" "b" "c" "b" "b" "b" "b" "b" "c" "c" "c" "c" "d"
PhillipD
  • 1,797
  • 1
  • 13
  • 23