user6498650 user6498650 - 28 days ago 6
R Question

Data.frame in R: concatenation of two column, numbers instead of occurrences

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

Answer

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"
Comments