简体   繁体   中英

R coerce data frame to numeric

RandomForest has returned object, prd, which is class numeric with indices:

> prd
      298       252       373       117         0        16       442        74 
4397.9232 1826.1264 1787.1963 1388.8097 1075.7217  873.9856 1602.7068 1775.1237 
class(prd)
[1] "numeric"

I want to do a correlation test, which means getting obs in the same format. Currently, obs is a one-column data frame:

> obs
       e2004MeanY
298       4261
252       1821
373       1710
117       1138

How do I convert obs to the correct format? I can't figure out how to tie the indices to the values in a numeric.

You can subset a data frame using [ which, as the default is drop = TRUE will drop the empty dimension thus going from a 1 column data frame to a numeric vector. Eg

R> obs <- data.frame(e2004MeanY = c(4261,1821,1712,1138))
R> rownames(obs) <- c(268,252,373,117)
R> 
R> (obs1 <- obs[, 1]) ## equiv of: obs[, 1, drop = TRUE]
[1] 4261 1821 1712 1138
R> class(obs1)
[1] "numeric"

If the losing of the row names is an issue then add them back as the names of the vector:

R> names(obs1) <- rownames(obs)
R> obs1
 268  252  373  117 
4261 1821 1712 1138

Of course, this isn't an issue if you use a temporary object when you call cor() , for example:

cor(prd, obs[, 1])

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