0
id    <- c('1','1','1','2','2','3')
name  <- c('myfile_1','myfile_2','myfile_4','myfile_1','myfile_2','myfile_3')
count <- c(5,4,2,1,3,1)
input <- data.frame(id, name, count)

Having a dataframe as input as the previous one.

id     name count
 1 myfile_1     5
 1 myfile_2     4
 1 myfile_4     2
 2 myfile_1     1
 2 myfile_2     3
 3 myfile_3     1

How is it possible to have a new dataframe like this:

id myfile_1 myfile_2 myfile_3 myfile_4
1    5        4         0        2
2    1        2         0        0
3    0        0         1        0    
Karolis Koncevičius
  • 9,417
  • 9
  • 56
  • 89
Pozmanski
  • 181
  • 11

1 Answers1

1
library(tidyverse);
input %>%
   spread(name, count, fill = 0);
#  id myfile_1 myfile_2 myfile_3 myfile_4
#1  1        5        4        0        2
#2  2        1        3        0        0
#3  3        0        0        1        0

More details (other than the link given in the duplicate flag) on long-to-wide conversion can be found here.

Maurits Evers
  • 49,617
  • 4
  • 47
  • 68