Stack of two columns

I have simple data, and I want to combine two columns, but in a certain way. Unfortunately, I did not find a way to solve my problem, even if it looks pretty simple. Therefore, my data looks 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
+4
source share
6 answers

Here is a solution with a R base:

d <- read.table(header=TRUE, text=
"Numbers Groups
1 A
2 A
3 B
4 C
5 C")

unlist(lapply(split(d, d$Groups), function(x) c(x$Numbers, as.character(x$Groups[1]))))
#  A1  A2  A3  B1  B2  C1  C2  C3 
# "1" "2" "A" "3" "B" "4" "5" "C" 
+1
source

Given that they Numbersare unique, then

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

Numbers, (, Numbers = c(1, 1, 3, 4, 5)), transform make.unique . sub make.unique ( unique, @Jaap , ),

sub('\\..*' ,'',unique(c(t(transform(df4, numbers = make.unique(as.character(numbers))))), 
                                                                          fromLast = TRUE))
#[1] "1" "1" "A" "3" "B" "4" "5" "C"
+4

Map

lst <- split(df1$Numbers, df1$Groups)
unlist(Map(`c`, lst, names(lst)), use.names = FALSE)
#[1] "1" "2" "A" "3" "B" "4" "5" "C"
+3

:

d2 <- aggregate(V1 ~ V2, d, paste0, collapse = ',')

strsplit(do.call(paste, c(d2[2:1], sep = ',', collapse = ',')),',')[[1]]

:

[1] "1"  "2"  "A"  "33" "B"  "4"  "5"  "C" 

@docendodiscimus: , , .


:

d <- read.table(text="1 A
2 A
2 A
33 B
4 C
5 C", header=FALSE)
+2

sapply. V1 , c.

unlist(sapply(unique(df$V2), function(x) c(df$V1[df$V2 %in% x], x),
                                                        USE.NAMES = FALSE))

#[1] "1" "2" "A" "3" "B" "4" "5" "C"
+2

100% - tidyverse:

library(tidyverse)
df %>%
  group_by(Groups) %>%
  summarize(output= list(c(Numbers,Groups[1]))) %>%
  unnest(output) %>%
  pull(output)

# [1] "1" "2" "A" "3" "B" "4" "5" "C"

:

unname(unlist(t(nest(df,Numbers)[2:1]))

, , 100% :

with(aggregate(Numbers ~ Groups,df,list),unlist(Map(c,Numbers,Groups),use.names = F))

unlist(by(df,df$Groups,function(x) c(x$Numbers,x$Groups[1])),use.names = F)
0

Source: https://habr.com/ru/post/1671022/


All Articles