I am working with the following data:
data <- data.frame(id=c(1811,1811,1522,7121),
pregunta=c("17", "17", "20", "21"),
valor=c("13","2","12","15"))
id pregunta valor
1811 17 13
1811 17 2
1522 20 12
7121 21 15
And I would like to make a transformation to obtain:
id p17.1 p17.2 p20 p21
1: 1811 13 2 NA NA
2: 1522 NA NA 12 NA
3: 7121 NA NA NA 21
Also, if the example were this:
data <- data.frame(id = c(1811, 1811, 1522,1366, 7121),
pregunta = c("17", "17","20","21", "21"),
valor = c("13", "2", "12","21", "15"))
The desired solution would be:
id p17.1 p17.2 p20 p21
1811 13 2 NA NA
1522 NA NA 12 NA
1366 NA NA NA 21
7121 NA NA NA 15
I use:
library(tidyverse)
data %>%
gather(valor, -'id', -pregunta) %>%
spread(pregunta, valor)
But having duplicate values I get the following error:
Error: Duplicate identifiers for rows (1, 2)
In addition: Warning message:
attributes are not identical across measure variables;
they will be dropped
I am interested in creating as many variables as the variable has Question, the problem is that when you repeat values of Question, you give that error.
I have tried other ways but in the end I always get to the problem of duplicate values.