Why am I facing the error when I try to convert long data set into wide data set? Please help my dear friends

The dataset is table2 in the tidyr package.

Here is the code.

library(tidyr)
#Converting a wide dataset into long dataset
long_data <- gather(table2,
key="variable",
value="value",
year:count)
as.data.frame(long_data)

#Converting the above long data set to a wide dataset again
wide_data <- spread(long_data, variable, value) -----> This is where I'm facing errors

Did you look at rows flagged by the error? It's a common mistake and error message even suggests a way to fix it.

Also, take a look here - https://www.daeconomist.com/post/2018-05-15-spread/

1 Like

It seems it flagged all the rows not sure why I've used the standard code and still got errors

Brother, that's what I got after following the instructions in error. Not much useful:(

Please, don't post screenshots, it's very difficult to help you with them. It's much easier to help you if you provide a reprex.

If you've never heard of a reprex before, you might want to start by reading this FAQ:

Could you give a summary of your dataframe "table2"?

The dataset is table2 in the tidyr package.

Here is the code.

library(tidyr)
#Converting a wide dataset into long dataset
long_data <- gather(table2,
key="variable",
value="value",
year:count)
as.data.frame(long_data)

#Converting the above long data set to a wide dataset again
wide_data <- spread(long_data, variable, value) -----> This is where I'm facing errors.

It is in the tidyr package

Here is the screenshot if you like

The problem is that there are identical rows in the long_data. At the first glance, you see that the rows 1 and 2, 3 and 4, 5 and 6, so on are all the same. When you try to convert this data frame into a wide format, it gets confused. In other words, the problem lies not in the last command but in the code creating the long_data.

1 Like

Gotcha but is there a way to convert this into a wide data set?

I changed your code like this. I hope it helps:

long_data <- gather(table2, key = "variable", value = "value", count, - c(country, year))
as.data.frame(long_data)
wide_data <- spread(long_data, variable, value)

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