Error in data.frame(): arguments imply differing number of rows: 1434, 3671, 3367

I am trying to use the quant mod library to get stocks' values and using gtrends library compare them, however, I haven't reached the second part of my analysis because I am stuck trying to understand and fix my problem. The code is as follows:

#Loading the libraries that I will start using to analyze the data
library(quantmod)
library(dplyr)
library(tidyverse)
library(tidyr)
#Getting stock tickers for: Square, Wells Fargo, JPMorgan Chase, Visa, and Mastercard
getSymbols(c("SQ", "JPM", "WFC", "V", "MA"))
#Merging the stock data into one data frame
stocks <- data.frame( "Square" = SQ$SQ.Close, "JPMorgan" = JPM$JPM.Close, "WellsFargo" = WFC$WFC.Close, "Visa" = V$V.Close, "Mastercard" = MA$MA.Close, "Date" = as.Date(row.names(as.data.frame(SQ)))) 

plotting <- stocks %>% gather(key = "stock", value = "value", -Date)

plotting %>% ggplot() + geom_line(aes(x = Date, y = value, color = stock)) + 
  scale_color_discrete(name = "Company", labels = c("JPMorgan", "Mastercard", "Square", "Visa", "Wells Fargo")) +
  labs(title = "Stock Prices of Financial Companies", y = "Stock Price")

You need to check the length of the vectors you are using to build the data frame. Run

length(SQ$SQ.Close)
length(JPM$JPM.Close)

and so one for all of the other ticker symbols. If they are not the same length, they will cause that error when you try to make the data frame.

Thank you so much, I will check it and write back. In case it is different lengths, how can I fix them?

I am not familiar with the data structures you are using but it looks like you could make a data frame for each symbol with columns for the stock symbol, the Date, and the closing price. Then you could bind all of those data frames into one using the rbind() function. That would leave you with a data frame similar to the one named plotting in your original code and you could use that in ggplot.

DFSQ <- data.frame(stock = "SQ", Date = as.Date(row.names(as.data.frame(SQ))), value = SQ$SQ.Close)
DFJPM <- data.frame(stock = "JPM", Date = as.Date(row.names(as.data.frame(JPM))), value = JPM$JPM.Close)
plotting <- rbind(DFSQ, DFJPM)

Thank you very much, your help really solved my problem!

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.