Home > Software design >  Reshaping in R: grouping vectors after merge
Reshaping in R: grouping vectors after merge

Time:11-13

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.

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!

CodePudding user response:

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

CodePudding user response:

Here is a another option using pivot_longer() and converting the 1,2,3 column names into factors labeled A, B, C

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

library(dplyr)
library(tidyr)

#basic answer:
answer<-pivot_longer(df, cols=starts_with("V"),  names_to = "Group")

OR
Answer changing the column names to a different label

answer<-pivot_longer(df, cols=starts_with("V"), names_prefix = "V", names_to = "Group")
answer$Group <- factor(answer$Group, labels = c("A", "B", "C")) 
answer %>% arrange(Group, value)
  • Related