How to covert columns of a data.frame to numeric vectors

Viewed 43
data1 <- structure(list(y = c(0.786495547305097, -0.275294469743402, 5.01043554797471, 
3.80786336657872, 2.13918082927747), x1 = c(1.26295428488079, 
-0.326233360705649, 1.3297992629225, 1.2724293214294, 0.414641434456408
), x2 = c(-0.729979080566544, -0.977769604136991, 1.60183697933767, 
0.911948278954854, 0.879294677497606), x3 = c(-0.39000956273028, 
-1.81922223008177, 0.659180710219526, 0.459621672673119, 1.6166263368295
)), row.names = c(NA, 5L), class = "data.frame")

data2 <- structure(list(V8 = c(-1.72904385751157, -1.07084107622855, 0.485233893853134, 
-0.512561121790257, -0.584170977530818), V9 = c(-0.370376604243532, 
-0.264930923072872, 0.815334082977478, -0.188695978779318, -1.58942168300819
), V10 = c(-0.154982593979532, 1.29764064456055, -0.851074132826296, 
0.496249346485277, -1.72196830424353), y = structure(c(-1.33203440383281, 
0.117885549592542, 4.36303461564377, 0.572854292213718, -0.627729381607459
), .Dim = c(5L, 1L), .Dimnames = list(c("1", "2", "3", "4", "5"
), NULL))), row.names = c("1", "2", "3", "4", "5"), class = "data.frame")

I have 2 data sets. Both are of class data.frame

> class(data1)
[1] "data.frame"
> class(data2)
[1] "data.frame"

However, the columns in data1 are of type numeric, whereas those in data2 are of type matrix.

> class(data1$y)
[1] "numeric"
> class(data2$y)
[1] "matrix" "array"

How can I convert the columns in data2 to class numeric like those in data1?

4 Answers

It could be a result of scaleing operations creating a matrix column. An easy option is to call data.frame again with do.call

data2 <- do.call(data.frame, data2)
class(data2$y)
#[1] "numeric"

Or convert to matrix and then to data.frame as matrix conversion removes the attributes

as.data.frame(as.matrix(data2))

Or another option is to loop over the columns with lapply, convert to numeric again

data2[] <- lapply(data2, as.numeric)

Here is a way.
If you run

data2[ -ncol(data2) ]
data2[[ ncol(data2) ]]

you will see that the last column is an object of class "matrix", like it is said in the question. So that column can be binded to the rest of the data.frame.

data3 <- cbind(data2[ -ncol(data2) ], y = data2[[ ncol(data2) ]])
str(data3)
#'data.frame':  5 obs. of  4 variables:
# $ V8 : num  -1.729 -1.071 0.485 -0.513 -0.584
# $ V9 : num  -0.37 -0.265 0.815 -0.189 -1.589
# $ V10: num  -0.155 1.298 -0.851 0.496 -1.722
# $ y  : num  -1.332 0.118 4.363 0.573 -0.628

concatenating.

r <- as.data.frame(lapply(data2, c))
str(r)
# 'data.frame': 5 obs. of  4 variables:
# $ V8 : num  -1.729 -1.071 0.485 -0.513 -0.584
# $ V9 : num  -0.37 -0.265 0.815 -0.189 -1.589
# $ V10: num  -0.155 1.298 -0.851 0.496 -1.722
# $ y  : num  -1.332 0.118 4.363 0.573 -0.628

Try the code like below

data2 <- list2DF(Map(c, data2))

or

data2 <- list2DF(Map(unlist, data2))
Related