Home > Software design >  add one column under another and assign a group to it
add one column under another and assign a group to it

Time:09-21

My data.frame

structure(list(a = c("12", "asd", "zxc", "123"), b = c("45", 
"qwe", "curced", "64"), c = c("78", "tyu", "454", "76")), class = "data.frame", row.names = c(NA, 
-4L))

I would like to add one column under the other and assign and assign groups to the columns. For example, for the first column "1" for the second front "2" for the third moved "3", etc. I know how to transfer columns one under another, but I do not know how to assign groups to them

What I want to get:

enter image description here

CodePudding user response:

If I understood, here a two different approaches

library(tidyverse)

1-) Comparing name to vector letters

Here I compare each name to their position in the alphabet, using the vector letters

df %>% 
  pivot_longer(cols = everything()) %>% 
  rowwise() %>% 
  mutate(group = which(name == letters))

2-) Create a auxiliar data.frame

In this alternative a create a data.frame with the variables name and group

df %>% 
  pivot_longer(cols = everything()) %>% 
  left_join(
    tibble(
      name = c("a","b","c"),
      group = 1:3
    )
  )

# A tibble: 12 x 3
   name  value  group
   <chr> <chr>  <int>
 1 a     12         1
 2 b     45         2
 3 c     78         3
 4 a     asd        1
 5 b     qwe        2
 6 c     tyu        3
 7 a     zxc        1
 8 b     curced     2
 9 c     454        3
10 a     123        1
11 b     64         2
12 c     76         3

CodePudding user response:

Base R approach using Map

result <- do.call(rbind, Map(data.frame, a = df, group = seq_along(df)))

Another approach using tidyverse functions.

library(dplyr)
library(tidyr)

df %>%
  pivot_longer(cols = everything(), names_to = 'group') %>%
  mutate(group = match(group, unique(group))) %>%
  arrange(group)

#   group value 
#   <int> <chr> 
# 1     1 12    
# 2     1 asd   
# 3     1 zxc   
# 4     1 123   
# 5     2 45    
# 6     2 qwe   
# 7     2 curced
# 8     2 64    
# 9     3 78    
#10     3 tyu   
#11     3 454   
#12     3 76    
  • Related