I need to transform this dataset where there is a column/date and a row/variable/name:
Variable 1 (%), Variable 2($):
| Name | Date 1 | Date 2 | Date 3 |
|---|---|---|---|
| Name1 | Value11% | Value12% | Value13% |
| Name2 | Value21% | Value22% | Value23% |
| Name3 | Value31% | Value32% | Value33% |
| Name1 | Value11$ | Value12$ | Value13$ |
| Name2 | Value21$ | Value22$ | Value23$ |
| Name3 | Value31$ | Value32$ | Value33$ |
To become a dataset where there is a column/variable and a row/date/name:
Consolidated dataset:
| Name | Date | Variable 1 | Variable 2 |
|---|---|---|---|
| Name1 | Date 1 | Value11$. | Value11%. |
| Name1 | Date 2 | Value12$. | Value12%. |
| Name1 | Date 3 | Value13$. | Value13%. |
| Name2 | Date 1 | Value21$. | Value21%. |
| Name2 | Date 2 | Value22$. | Value22%. |
| Name2 | Date 3 | Value23$. | Value23%. |
| Name3 | Date 1 | Value31$. | Value31%. |
| Name3 | Date 2 | Value32$. | Value32%. |
| Name3 | Date 3 | Value33$. | Value33%. |
Right now, I have tried to use the first data set with the function melt with the name as id:
melt(data, id="Name)
Unfortunately, I have this error message: Error in match.names(clabs, names(xi)) : names do not match previous names
Which can be the mistake? Are there any other options to achieve my goal?
Alternatively, I have tried to import the data from the two variables in two different datasets and have used rbind to integrate them and checck through the indetical function if the column names were the sames and the result was TRUE. I do not know which can be the reason for this error.
Thank you so much for any help folks!
Data:
data <- data.frame(
stringsAsFactors = FALSE,
Name = c("Name1", "Name2", "Name3", "Name1", "Name2", "Name3"),
Date.1 = c("Value11%","Value21%",
"Value31%","Value11$","Value21$","Value31$"),
Date.2 = c("Value12%","Value22%",
"Value32%","Value12$","Value22$","Value32$"),
Date.3 = c("Value13%","Value23%",
"Value33%","Value13$","Value23$","Value33$")
)
Instead of using
melt()andcast()from thereshape2package it is recommened to usepivot_wider()andpivot_longer()from thetidyrpackage for pivoting/reshaping between wide and long data formats.Here is what that could look like for your data: