cbind replaces String with number?

user2071938 picture user2071938 · May 9, 2014 · Viewed 10.1k times · Source
x = iris$Sepal.Width;
y = iris$Species;

m = cbind(x,y);

the output of m is:

        x  y
  [1,] 3.5 1
  [2,] 3.0 1
  [3,] 3.2 1
  [4,] 3.1 1
  [5,] 3.6 1
  [6,] 3.9 1

but I want 'setosa', etc in column y instead of a number

how can I do that?

I want to combine the 2 Vectors because I want to filter afterwards with

m[m[,"y"]=="virginica",]

or is ther another oportunity to do that without cbind?

Answer

A5C1D2H2I1M1N2O1R2T1 picture A5C1D2H2I1M1N2O1R2T1 · May 9, 2014

For vectors being combined with cbind, the result would be a matrix, which can only hold one type of data. Thus, the "Species" factor gets coerced to its underlying numeric value.

Try cbind.data.frame instead (or just data.frame) if you need your columns to have different data types.

> head(data.frame(x, y))
    x      y
1 3.5 setosa
2 3.0 setosa
3 3.2 setosa
4 3.1 setosa
5 3.6 setosa
6 3.9 setosa
> head(cbind.data.frame(x, y))
    x      y
1 3.5 setosa
2 3.0 setosa
3 3.2 setosa
4 3.1 setosa
5 3.6 setosa
6 3.9 setosa