0

I have a dataset (questionnaire_demo) with a lot of variables. I want to select some of them (Participant.Private.ID, UTC.Date, Question.Key, Response), filtering for some values (gender, age, country) of Question.Key.

I have selected something like this.

     Participant.Private.ID     UTC.Date      Question.Key   Response
1           xxxx              16/02/2022          gender        F
2           xxxx              16/02/2022            age         20
3           xxxx              16/02/2022          country       IT

My trouble is: I don't want to select Question.Key and Response in this form; I want to convert column values of col_1 as column names and column values of col_2 would be the column values associated with the column names. So, I want to obtain a new disposition like:

     gender   age    country
1      F       20       IT

and include these new columns in the selection. So I'll have something like, a row for participant:

   Partecipant.Private.ID    UTC.Date    gender   age   country
1          xxxx             16/02/2022     F       20      IT

I've tried something like this:

library(reshape2)
questionnaire_demo <- questionnaire_demo %>%
  filter(Question.Key == "gender" | Question.Key == "age" | Question.Key == "country") %>%
new_resp_demo <- dcast(questionnaire_demo, Response ~ Question.Key)
  select(Participant.Private.ID, UTC.Date, new_resp_demo)

but it doesn't work.

Can anyone help me, please?

Septale
  • 15
  • 4
  • It would be helpful to have a minimal data set to better understand its structure. – POC Feb 16 '22 at 16:52
  • after filtering for `gender, age, country`, I obtain a dataset that looks like: ` Partecipant.Private.ID UTC.Date Question.Key Response 1 xxxx 16/02/2022 gender F 2 xxxx 16/02/2022 age 20 3 xxxx 16/02/2022 country IT ` – Septale Feb 16 '22 at 16:59
  • After filtering, `tidyr::pivot_wider(df, names_from = Question.Key, values_from = Response)` should work. – Gregor Thomas Feb 16 '22 at 17:00
  • I have no problem filtering the data, but I can't modify `Question.Key` and `Response` as I said in the question – Septale Feb 16 '22 at 17:02

0 Answers0