0

I am trying to convert my dataset from wide to long format using dcast. I start by reading in my file as a CSV (read_SelectionModel). The code that I have been trying is below:

x = colnames(read_SelectionModel[,3:241])
t = melt(read_SelectionModel, id.vars = c("Ratio", "Ticker"), measure.vars = x, variable.name = "Dates", value.name = "Ratio Value")
r_traverse2 = dcast(t, Dates + Ticker ~ Ratio, value.var = "Ratio Value", fun.aggregate = sum, na.rm = TRUE)

I have two id.vars variables Ratio and Ticker in order to have each ratio correspond to each stock's ticker. Having measure.vars = x, and variable.name = "Dates". I am creating a new column called "Ratio Value" that will hold the data for each ratio/stock.

Using r_traverse2 I have been using dcast to try to go from wide to format but I have been getting the following error:

"Error in .fun(.value[0], ...) : invalid 'type' (character) of argument".

I have tried to adjust fun.aggregate but keep getting the same error as well as the fun function not being found. How can I go about fixing this?

I have tried fun.aggregate = sum, fun.aggregate = mean, and I have also tried not specifying fun.aggregate argument. If I do not specify this, it defaults to a length where my observations are 0's and 1's instead of the ratio/stock data I want.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
meech
  • 1
  • 1
  • 2
    Please include enough code for a minimum reproducible example. This helps people help you. https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example You have a Python tag on your question, but you seem to be using R. Please clarify that as well. – John Polo Dec 10 '22 at 23:27
  • Hello, thank you for comment and the helpful link for future questions. This is the only code that I have for transposing my data except for reading in a CSV file. I am following this source https://www.listendata.com/2016/01/transpose-data-in-r.htmlspecifically "Convert Wide Format Data to Long Format" and "Example 2 : More than 1 ID Variable" under Convert Long to Wide Format. I am doing this essentially two times between long and wide with more than 1 ID variable. – meech Dec 12 '22 at 05:03
  • The goal is to get Dates, Ticker, Ratio, and Ratio Value to be in a long format. My current dataset is in a wide format. – meech Dec 12 '22 at 05:17
  • That can't be all of your code. You are using the functions `melt()` and `dcast()` which are not part of base R. That means you're loading a package and you haven't indicated which one. There are multiple functions to read in CSV, but there is no way to tell how you did it. These all indicate you're not including all of your code. Also, if you are copying code from a website (you included a link in one of your comments), we don't know exactly which part of that you have tried. Additionally, the link I included in my first comment says that you should include some of your data. – John Polo Dec 12 '22 at 19:04

0 Answers0