Create variables and fill in information from other variables

Asked

Viewed 58 times

1

Software R. I would like to know how to create variables through information contained in a variable and then fill in information that is in two other existing ones. Example

Como esta

I’d like to keep it that way Como eu gostaria que estivesse

Excuse the way of the question, I’m learning. Images are examples

  • 1

    Try to put your data in a format that is easily playable by OS users. You can keep the images for easy viewing, but try running dput(head(seus.dados)) and paste the output into the question.

1 answer

4


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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.