简体   繁体   中英

Error: (list) object cannot be coerced to type 'double' with multiple variables

I have data with multiple variables. I tried to covert my data to numeric (each variable). I have tried as.numeric , but I got an error:

Error: (list) object cannot be coerced to type 'double' .

I also tried as.matrix , and it is fine. But I still need to convert my data to numeric. So, I tried as.numeric(unlist(iris[,1:4])) , but it is not what I want. Here is my try:

data("iris")
    iris[,1:4]
    > is.data.frame(iris[,1:4])
      [1] TRUE
    > is.numeric(iris[,1:4])
    [1] FALSE

This is not what I want.

> as.numeric(unlist(iris[,1:4]))
     [1] 5.1 4.9 4.7 4.6 5.0 5.4 4.6 5.0 4.4 4.9 5.4 4.8 4.8 4.3 5.8     5.7 5.4 5.1 5.7 5.1 5.4 5.1 4.6 5.1 4.8 5.0 5.0 5.2 5.2 4.7
 [31] 4.8 5.4 5.2 5.5 4.9 5.0 5.5 4.9 4.4 5.1 5.0 4.5 4.4 5.0 5.1 4.8 5.1 4.6 5.3 5.0 7.0 6.4 6.9 5.5 6.5 5.7 6.3 4.9 6.6 5.2
 [61] 5.0 5.9 6.0 6.1 5.6 6.7 5.6 5.8 6.2 5.6 5.9 6.1 6.3 6.1 6.4 6.6 6.8 6.7 6.0 5.7 5.5 5.5 5.8 6.0 5.4 6.0 6.7 6.3 5.6 5.5
 [91] 5.5 6.1 5.8 5.0 5.6 5.7 5.7 6.2 5.1 5.7 6.3 5.8 7.1 6.3 6.5 7.6 4.9 7.3 6.7 7.2 6.5 6.4 6.8 5.7 5.8 6.4 6.5 7.7 7.7 6.0

I would like to have it like this (without the name of the variables):

                [,1]        [,2]        [,3]        [,4]
[1,]            5.1         3.5          1.4         0.2
[2,]            4.9         3.0          1.4         0.2
[3,]            4.7         3.2          1.3         0.2
[4,]            4.6         3.1          1.5         0.2

I need to remove the name of variables and make it as a matrix as above . any help, please?

We can do:

res<-sapply(iris[,-5], as.numeric)
attr(res,"dimnames") <- NULL

Or as @markus suggests simply:

unname(as.matrix(iris[,1:4]))

Result:

       [,1] [,2] [,3] [,4]
  [1,]  5.1  3.5  1.4  0.2
  [2,]  4.9  3.0  1.4  0.2
  [3,]  4.7  3.2  1.3  0.2
  [4,]  4.6  3.1  1.5  0.2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM