Home > OS >  Create a dataframe with a column that will include unique values of a column and unique column names
Create a dataframe with a column that will include unique values of a column and unique column names

Time:12-10

I have the dataframe below:

dummy<-structure(list(Name = c("A", "B", "C", "A", "B", "C"), `#BISB` = c(2, 
6, 4, 0, 4, 6), `#BISC` = c(2, 6, 4, 0, 4, 6), `#BISD` = c(2, 
6, 4, 0, 4, 6), `#BISE` = c(2, 6, 4, 0, 4, 6), `#BISF` = c(2, 
6, 4, 0, 4, 6), `#BISG` = c(2, 6, 4, 0, 4, 6), `#BISH` = c(2, 
6, 4, 0, 4, 6)), row.names = c(NA, -6L), class = c("tbl_df", 
"tbl", "data.frame"))

and I would like to reshape it in a nodes dataframe. This nodes dataframe should contain one column named id with index numbers (1,2,3...) and the second column will be named group and it will contain all the unique values of the column Name and all the unique column names except from the column Name from the dummy dataframe like:

id group
1   1     A
2   2     B
3   3     C
4   4 #BISB
5   5 #BISC
6   6 #BISD
7   7 #BISE
8   8 #BISF
9   9 #BISG
10 10 #BISH

CodePudding user response:

We may create a tibble with summarise by taking the unique values of 'Name', concatenate (c) with the column names except the first and then create the 'id' as the sequence (row_number())

library(dplyr)
dummy %>% 
  summarise(group = c(unique(Name), names(.)[-1])) %>%
  mutate(id = row_number(), .before = 1)

-output

# A tibble: 10 × 2
      id group
   <int> <chr>
 1     1 A    
 2     2 B    
 3     3 C    
 4     4 #BISB
 5     5 #BISC
 6     6 #BISD
 7     7 #BISE
 8     8 #BISF
 9     9 #BISG
10    10 #BISH

Or more easily

out <- data.frame(group = c(unique(dummy$Name), names(dummy)[-1]))
out$id <- seq_len(nrow(out))
  •  Tags:  
  • r
  • Related