Create variables and fill in information from other variables

1

Software R. I would like to know how to create variables through information contained in one variable and then populate with information that is in two other variables. Example

Iwouldlikeittostaythatway

Sorry for the way the question is, I'm learning. Images are examples

    
asked by anonymous 17.07.2018 / 03:10

1 answer

4

The reshape2::dcast function does what it needs. You only have to run it once for each semester and merge the data:

dados <- data.frame(
  id = c(rep(9039, 2), rep(8234, 2)),
  semestre_1 = paste(1, 2018:2017, sep = '_'),
  semestre_2 = paste(2, 2018:2017, sep = '_'),
  para_1s = 1:4,
  para_2s = 5:8
)

> dados
    id semestre_1 semestre_2 para_1s para_2s
1 9039     1_2018     2_2018       1       5
2 9039     1_2017     2_2017       2       6
3 8234     1_2018     2_2018       3       7
4 8234     1_2017     2_2017       4       8

library(reshape2)
sem1 <- dcast(dados, id ~ semestre_1, value.var = 'para_1s')
sem2 <- dcast(dados, id ~ semestre_2, value.var = 'para_2s')

> merge(sem1, sem2)
    id 1_2017 1_2018 2_2017 2_2018
1 8234      4      3      8      7
2 9039      2      1      6      5
    
17.07.2018 / 05:33