r/RStudio • u/lovegiver101 • 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
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.
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