0

There is a table:

class<-c("A","B", "B","C","D","D","D")
value<-c(1,3,2,5,6,2,5)
df<-cbind(class,value)

enter image description here

For example, the classes "B" and "C" have more than one value. I want to set every value of the class into a separate column. I would like to get the following output:

enter image description here

Could You please help me?

Thanks in advance, Best regards, Inna

Inna
  • 115
  • 12

2 Answers2

3

This might help:

First of all, make it a dataframe using data.frame()

class <- c("A","B", "B","C","D","D","D")
value <- c(1,3,2,5,6,2,5)
df <- data.frame(class,value)

# A bunch of packages that might help you.
library(tidyverse)

df %>%
    group_by(class) %>%
    mutate(new_names = paste0("value", 1:n())) %>%
    pivot_wider(names_from = new_names)

Output:

# A tibble: 4 x 4
# Groups:   class [4]
  class value1 value2 value3
  <chr>  <dbl>  <dbl>  <dbl>
1 A          1     NA     NA
2 B          3      2     NA
3 C          5     NA     NA
4 D          6      2      5

(I would not put 0 - NA is the specific solution if a value is missing)

Georgery
  • 7,643
  • 1
  • 19
  • 52
2

You can use split and rbind and fill the missing with lapply and [:

x <- split(df[,2], df[,1])
do.call("rbind", lapply(x, "[", 1:max(lengths(x))))
#  [,1] [,2] [,3]
#A "1"  NA   NA  
#B "3"  "2"  NA  
#C "5"  NA   NA  
#D "6"  "2"  "5" 
GKi
  • 37,245
  • 2
  • 26
  • 48