bli
bli

Reputation: 79

Is there a way to resolve this error in R, data frame warning

I am trying to create a data frame for my analysis but I'm getting two errors and despite all the research or edits, I have tried it's not working. when I ran this code im getting warnings

Treasury = data.frame(Treasury2$DGS_2,Treasury3$DGS_3,Treasury5$DGS_5,
+  Treasury7$DGS_7,Treasury10$DGS_10,Treasury30$DGS_30)
> colnames(Treasury) = c("Date","DGS_2","DGS_3","DGS_5","DGS_7","DGS_10","DGS_30")
Error in names(x) <- value : 
  'names' attribute [7] must be the same length as the vector [6]
> 

this is my code up to this level

library(readxl)
library(tidyverse)
library(tidyquant)
library(matrixStats)
library(YieldCurve)
library(tseries)

Treasury2 = read_excel("DGS_2.xlsx", col_names = TRUE)
Treasury3 = read_excel("DGS_3.xlsx", col_names = TRUE)
Treasury5 = read_excel("DGS_5.xlsx", col_names = TRUE)
Treasury7 = read_excel("DGS_7.xlsx", col_names = TRUE)
Treasury10 = read_excel("DGS_10.xlsx", col_names = TRUE)
Treasury30 = read_excel("DGS_30.xlsx", col_names = TRUE)


GLD = read.csv("GLD.csv", header = TRUE)
IEFA = read.csv("IEFA.csv", header = TRUE)

gld = Return.calculate(xts(GLD$Adj.Close, order.by = as.Date(GLD$Date)), method = c("log"))
iefa = Return.calculate(xts(IEFA$Adj.Close, order.by = as.Date(IEFA$Date)), method = c("log"))
Treasury = data.frame(Treasury2$DGS_2,Treasury3$DGS_3,Treasury5$DGS_5, Treasury7$DGS_7,Treasury10$DGS_10,Treasury30$DGS_30)
colnames(Treasury) = c("Date","DGS_2","DGS_3","DGS_5","DGS_7","DGS_10","DGS_30")

what mistakes am I making when creating a data frame? thanks for the support in advance.

Upvotes: 0

Views: 232

Answers (2)

akrun
akrun

Reputation: 886938

We can use setNames

setNames(Treasury,  c("DGS_2","DGS_3","DGS_5","DGS_7","DGS_10","DGS_30"))

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388807

The error message suggests that you are passing column names of length 7 whereas your dataframe has only 6 columns. I think you don't have Date column in your dataframe.

Try with -

colnames(Treasury) = c("DGS_2","DGS_3","DGS_5","DGS_7","DGS_10","DGS_30")

Alternatively you can assign the column name while creating the dataframe.

Treasury = data.frame(DGS_2 = Treasury2$DGS_2,
                      DGS_3 = Treasury3$DGS_3,
                      DGS_5 = Treasury5$DGS_5,
                      DGS_7 = Treasury7$DGS_7,
                      DGS_10 = Treasury10$DGS_10,
                      DGS_30 = Treasury30$DGS_30)

Upvotes: 1

Related Questions