R: numeric vector becoming non-numeric after cbind of dates

Fabian Stolz picture Fabian Stolz · Jun 22, 2012 · Viewed 22k times · Source

I have a numeric vector (future_prices) in my case. I use a date vector from another vector (here: pred_commodity_prices$futuredays) to create numbers for the months. After that I use cbind to bind the months to the numeric vector. However, was happened is that the numeric vector become non-numeric. Do you know how what the reason for this is? When I use as.numeric(future_prices) I get strange values. What could be an alternative? Thanks

head(future_prices)
pred_peak_month_3a pred_peak_quarter_3a 
1           68.33907             62.37888
2           68.08553             62.32658

is.numeric(future_prices)
[1] TRUE
> month = format(as.POSIXlt.date(pred_commodity_prices$futuredays), "%m")
> future_prices <- cbind (future_prices, month)
> head(future_prices)
  pred_peak_month_3a     pred_peak_quarter_3a   month
  1 "68.3390747063745"   "62.3788824938719"     "01"
 is.numeric(future_prices)
 [1] FALSE 

Answer

johannes picture johannes · Jun 22, 2012

The reason is that cbind returns a matrix, and a matrix can only hold one data type. You could use a data.frame instead:

n <- 1:10
b <- LETTERS[1:10]
m <- cbind(n,b)
str(m)
 chr [1:10, 1:2] "1" "2" "3" "4" "5" "6" "7" "8" "9" ...
 - attr(*, "dimnames")=List of 2
  ..$ : NULL
  ..$ : chr [1:2] "n" "b"

d <- data.frame(n,b)
str(d)
'data.frame':   10 obs. of  2 variables:
 $ n: int  1 2 3 4 5 6 7 8 9 10
 $ b: Factor w/ 10 levels "A","B","C","D",..: 1 2 3 4 5 6 7 8 9 10