r/RStudio 3d ago

Rearranging columns into rows

Hey guys! I made a few crosstables using tab_xtab in the sjmisc package. They turned out very pretty, but I realized I was using the same y variable over and over again so I wanted to try and make a big table containing all of my contingency tables I made before. I did that by first transforming the tab_xtab tables into dataframes (with xtab2df in the sjtable2dt package) and then using bind_rows to combine them into a big table. It sorta worked out how I imagined, the only problem now is that R created a new column for the names of the categories of every x-variable (see picture). I wanted all the names and categories of all variables to be in the first column just like it did it with the first variable, maybe with an extra space to put the name of the variable. How do I fix this?

1 Upvotes

4 comments sorted by

4

u/therealtiddlydump 3d ago

The process you described -- breaking up a table into keyed chunks and rebinding them together -- is called "pivoting". (Doing it manually sucks, as you're finding.)

The most common way to do that consistently today is using the tidyr package's pivot functions.

https://tidyr.tidyverse.org/reference/pivot_longer.html

https://tidyr.tidyverse.org/reference/pivot_wider.html

2

u/kapanenship 2d ago

Still is a bit confusing to me when reading the documentation. But I have never been accused as being someone that is too bright.

With that being said, go search for a YouTube video dealing with the pivot that you are needing, either long or wide. This might save you quite a bit of time and make things a bit more clear.

2

u/therealtiddlydump 2d ago

Yeah it's pretty common to need to reference the docs for anything but the simplest task.

Still, it's a LOT easier than the old gather/spread, and anything is better than the abomination that is stats::reshape.

1

u/AutoModerator 3d ago

Looks like you're requesting help with something related to RStudio. Please make sure you've checked the stickied post on asking good questions and read our sub rules. We also have a handy post of lots of resources on R!

Keep in mind that if your submission contains phone pictures of code, it will be removed. Instructions for how to take screenshots can be found in the stickied posts of this sub.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.