Home > OS >  adding a column name in R
adding a column name in R

Time:12-17

library(quantmod)
quote<-c("0883.HK","0386.HK","0857.HK")
df1<-data.frame(getQuote(quote)$Last)

Just download the last traded price for some stocks and put those quotes in a data frame, and then what I am trying to do here is to add column names for those quotes like below:

colnames(df1)<-c("883","386","857")

Error in names(x) <- value : 
  'names' attribute [3] must be the same length as the vector [1]

May I ask what have I done wrong here? Million thanks.

CodePudding user response:

The data you selected is one column with three observations. Therefore you cannot assign it three names as there is only one column

> df1
  getQuote.quote..Last
1                10.00
2                 3.74
3                 3.55

CodePudding user response:

When we apply as.data.frame or data.frame on a vector (after extracting the Last column), it will be a single column with that vector as values of the column. We may need to convert to list and then setting the column names will work

df1 <- as.data.frame.list(getQuote(quote)$Last)
  • Related