Numeric values ​​of a column of a matrix modifiable when converted to data.frame

Starting on R 2.13, I want to have data.frame from several columns, the first of which has a numeric type, the other type of character. When I create my object, the values ​​of the first column are converted in such a way that I do not expect and do not understand. See code below.

tmp <- cbind (1:10, rep ("aa", 10))

Tmp

  [,1] [,2]
[1,] "1"  "aa"
[2,] "2"  "aa"
[3,] "3"  "aa"
[4,] "4"  "aa"
[5,] "5"  "aa"
[6,] "6"  "aa"
[7,] "7"  "aa"
[8,] "8"  "aa"
[9,] "9"  "aa"
[10,] "10" "aa"

tmp <- data.frame (tmp)

Tmp

   X1 X2
1   1 aa
2   2 aa
3   3 aa
4   4 aa
5   5 aa
6   6 aa
7   7 aa
8   8 aa
9   9 aa
10 10 aa

tmp [, 1] <- as.numeric (tmp [, 1])

Tmp

   X1 X2
1   1 aa
2   3 aa
3   4 aa
4   5 aa
5   6 aa
6   7 aa
7   8 aa
8   9 aa
9  10 aa
10  2 aa

For some reason, the values ​​of the first column are changing. I have to do something obviously wrong here, can someone tell me a workaround?

+3
source share
2 answers
> tmp <- data.frame(cbind(1:10,rep("aa",10)))
> str(tmp)
'data.frame':   10 obs. of  2 variables:
 $ X1: Factor w/ 10 levels "1","10","2","3",..: 1 3 4 5 6 7 8 9 10 2
 $ X2: Factor w/ 1 level "aa": 1 1 1 1 1 1 1 1 1 1

As you can see above, it is tmp$X1converted to a factor, which causes the behavior that you see.

Try:

tmp[,1] <- as.numeric(as.character(tmp[,1]))
+6

@aix - . , , , :

data.frame(1:10,rep("aa",10))

, cbind ing ( ), .

, , , , data.frame (X1.10 rep..aa...10.):

data.frame(var1=1:10,var2=rep("aa",10))

data.frame , :

data.frame(var1=1:10,var2="aa")

, , stringsAsFactors=FALSE wrap var2 I() (.. var2=I("aa"))

+5

All Articles