Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reshaping in R: grouping vectors after merge

I have a pretty basic problem that I can’t seem to solve:

Take 3 vectors:

V1 V2 V3
1 4 7
2 5 8
3 6 9

I want to merge the 3 columns into a single column and assign a group.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Desired result:

Group Value
A 1
A 2
A 3
B 4
B 5
B 6
C 7
C 8
C 9

My code:

V1 <- c(1,2,3)
V2 <- c(4,5,6)
V3 <- c(7,8,9)

data <- data.frame(group = c("A", "B", "C"),
                   values = c(V1, V2, V3))

Actual result:

Group Value
A 1
B 2
C 3
A 4
B 5
C 6
A 7
B 8
C 9

How can I reshape the data to get the desired result?

Thank you!

>Solution :

We can stack on a named list of vectors

stack(setNames(mget(paste0("V", 1:3)), LETTERS[1:3]))[2:1]

-output

ind values
1   A      1
2   A      2
3   A      3
4   B      4
5   B      5
6   B      6
7   C      7
8   C      8
9   C      9

Regarding the issue in the OP’s data creation, if the length is less than the length of the second column, it will recycle. We may need rep

data <- data.frame(group = rep(c("A", "B", "C"), c(length(V1), 
   length(V2), length(V3))),
                   values = c(V1, V2, V3))

-output

> data
  group values
1     A      1
2     A      2
3     A      3
4     B      4
5     B      5
6     B      6
7     C      7
8     C      8
9     C      9
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading