BaptM BaptM -4 years ago 119
R Question

Stack two columns

I got a simple data and I want to merge two columns but in a specific way. Unfortunately I didn't find a way to resolve my problem even if it looks pretty simple.
So my data looks like something like this:

Numbers Groups
1 A
2 A
3 B
4 C
5 C


In the end, I want to have something like this:

1
2
A
3
B
4
5
C

Answer Source

Given that Numbers are unique then,

v1 <- c(t(df4))
v1[!duplicated(v1, fromLast = T)]
#[1] "1" "2" "A" "3" "B" "4" "5" "C"

If there are duplicated Numbers, (lets say Numbers = c(1, 1, 3, 4, 5))then we can transform and make.unique prior to concatenating. sub can be used to remove decimals from make.unique (Using the unique approach mentioned by @Jaap in comments just to get everything in one go),

sub('\\..*' ,'',unique(c(t(transform(df4, numbers = make.unique(as.character(numbers))))), 
                                                                          fromLast = TRUE))
#[1] "1" "1" "A" "3" "B" "4" "5" "C"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download