he4dmuck
he4dmuck

Reputation: 1

How do I change the order of multiple grouped values in a row dependent on another variable in that row in R?

I need some help conditionally sorting/switching data based on a factor variable. I'm not sure if it's a typical use case I just can't formulate properly enough for a search engine to show me a solution or if it is that niche but I haven't found anything yet.

I currently have a dataframe like this:

id group  a1 a2 a3 a4  b1 b2 b3 b4
 1     1   2  6  6  3   4  4  6  4
 2     2   5  2  2  2   2  5  2  3
 3     1   6  3  3  1   3  6  4  1
 4     1   4  8  4  2   7  8  8  9
 5     2   3  1  1  4   2  1  1  7

For context this is from a psychological experiment where people went through two variations of a task and the order of those conditions was determined by the experimental group they were assigned to. The columns represent different measurements from different trials and are currently grouped together for the same variable and in chronological order, meaning a1,a2,a3,a4 are essentially the same variable at consecutive time points, same with b1,b2,b3,b4.

I want to split them up for the different conditions so regardless of which group (=which order of tasks) someone went through, data from one condition should come first in the dataframe and columns should still be grouped together for the same variables and in chronological order within that condition. It should essentially look like this:

id group  c1a1 c1a2 c2a1 c2a2  c1b1 c1b2 c2b1 c2b2
 1     1     2    6    6    3     4    4    6    4
 2     2     2    2    5    2     2    3    2    5
 3     1     6    3    3    1     3    6    4    1
 4     1     4    8    4    2     7    8    8    9
 5     2     1    4    3    1     1    7    2    1

So essentially for group 1 everything stays the same since they happened to go through the conditions in the same order that I want to have in the new dataframe while for group 2 values are being switched where the originally second half of values for each variable is put in front of the originally first one.

I hope I formulated the problem in a way, people can understand it.

My real dataset is a bit more complicated it has 180 columns minus id and group so 178. I have 13 variables some of which were measured over two conditions with 5 trials for each of those and some which have those 5 trials for each of the 2 main condition but which also have 2 adittional measurements for each condition where the order was determined by the same group variable.

(We essentially asked participants to do the task again in two certain ways, which allowed us to see if they were capable of doing them like that if they wanted to under the circumstences of both main conditions).

So there are an adittional 4 columns for some variables which need to be treated seperately. It should look like this when transformed (x and y are the 2 extra tasks where only b was measured once):

id group  c1a1 c1a2 c2a1 c2a2  c1b1 c1b2 c1bx c1by c2b1 c2b2 c2bx c2by
 1     1     2    6    6    3     4    4    3    7    6    4    4    2
 2     2     2    2    5    2     2    3    4    3    2    5    2    2
 3     1     6    3    3    1     3    6    2    2    4    1    1    1
 4     1     4    8    4    2     7    8    1    1    8    9    5    8
 5     2     1    4    3    1     1    7    8    9    2    1    3    4

What I want to say with this is, I need a pretty general solution.

I already tried formulating a function for creation of two seperate datasets for the groups and then merging them by id but got stuck with the automatic creation and naming of columns which I can't seem to wrap my head around. dplyr is currently loaded and used for some other transformations but since I'm not really good with it, I need to ask for your help regarding a solution with or without it. I'm still pretty new to R and this is for my bachelor thesis.

Thanks in advance!

Upvotes: 0

Views: 84

Answers (1)

Bobby Thomas
Bobby Thomas

Reputation: 91

Your question leaves a few things unclear that make this hard to answer, but here is maybe a start that could help, or at least help clarify your problem. It would really help if you could clarify 2 pieces of info, what types of column rearrangements you need, and how you distinguish what indicates that a row needs to have this transformation.

I'm also wondering if instead of trying to manipulate your data in its current shape, if it not might be more practical to figure out how to change the shape of your data to better represent your data, perhaps using something like pivot_longer(), I don't know how this data will ultimately be used or what the actual values indicate, but it doesn't seem to be very tidy in its current form, and instead having a "longer" table might be more meaningful, but I'll still provide what I think is a solution to your listed problem.

This creates some example data that looks like it reflects yours in the example table.

ID=seq(1:10)
group=sample(1:2,10,replace=T)
Data=matrix(sample(1:10,80,replace=T),nrow=10,ncol=8)

DataFrame=data.frame('ID'=ID,'Group'=group,Data)

You then define the groups of columns that need to be kept together. I can't tell if there is an automated way for you to indicate which columns are grouped, but this might get bulky if done manually. Some more information on what your column names actually are, and how they are distributed in groups would help.

ColumnGroups=list('One'=c('X1','X2'),'Two'=c('X3','X4'),'Three'=c('X5','X6'),'Four'=c('X7','X8'))

You can then figure out which rows need to have rearranged done by using some conditional. Based on your example, I'm assuming when the group variable equals 2, then the rearranging needs to be done, which is what I've used here.

FlipRows=DataFrame$Group==2

You can then have R only apply the rearrangement needed to those rows that need it, and define the rearrangement based on the ordering of the different column groups. I know you ask for a general solution, but is hard to identify the general solution you need without knowing what types of column rearrangements you need. If it is always flipping two sets of consecutive column groups, that would be easier to define without having to type it all out. What I have done here would require you to manually type out the order of the different column groups that you would like the rows to be rearranged as. The SortedDataFrame object seems to be what you are looking for, but might not actually reflect your real data. I removed columns 1 and 2 in this operation since those are ID and group which you don't want overridden.

SortedDataFrame=DataFrame

SortedDataFrame[FlipRows,-c(1,2)]=DataFrame[FlipRows,c(ColumnGroups$Two,ColumnGroups$One,ColumnGroups$Four,ColumnGroups$Three)]

This solution won't work if you need to rearrange each row differently, but it is unclear if that is the case. Try to provide any of the other info requested here, and let me know where this solution doesn't work for you, and that.

Upvotes: 1

Related Questions