-2

I made a new dataset which only have the variables:

I have then added a new variable to my data set, called Item:

d <- test[, . (ID, age, test= test)]

My question is now, that I want to make a function that will make a loop over all questions i have ? is that possible?

Hellihansen
  • 163
  • 6
  • do you have a sample of the `lmh14` so we can see what the data looked like before? – RyanF Aug 31 '22 at 12:45
  • I have made an example in the question :) – Hellihansen Aug 31 '22 at 12:52
  • 2
    What do you want to do in this loop? Most functions in R are vectorized so you usually don't need to write a look yourself. It's not clear to me what you are trying to do. It's easier to help you if you provide a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Aug 31 '22 at 12:53
  • And how would you like question number displayed in the output table? – RyanF Aug 31 '22 at 12:53
  • No i should not display in the output :) – Hellihansen Aug 31 '22 at 13:06

2 Answers2

2

Here is a sample set with only 2 questions. You can modify this to extend to 85.

In this case, I am using the melt( ) function in the data.table package to convert the data from wide format to long format. The id.vars are variables you would like to keep as columns and the measure.vars are variables you would like condensed into a new column Question with corresponding values in Response.

library(data.table)

lmh14 <- data.table(
  ID = c(1,2,3,4),
  education_code = c(20,50,20,60),
  age = c(87,67,56,52),
  sex = c("F","M","M","M"),
  question1 = c(NA_real_,1,5,3),
  question2 = c(4,3,5,NA_real_))

lmh14_v2 <- melt(
  data = lmh14,
  id.vars = c("ID","education_code","sex"),
  measure.vars = c("question1","question2"),
  variable.name = "Question",
  value.name = "Response")

lmh14_v2
   ID education_code sex  Question Response
1:  1             20   F question1       NA
2:  2             50   M question1        1
3:  3             20   M question1        5
4:  4             60   M question1        3
5:  1             20   F question2        4
6:  2             50   M question2        3
7:  3             20   M question2        5
8:  4             60   M question2       NA
RyanF
  • 119
  • 6
0

Although the assign function is not the best, here is a loop that can do this for you.

for (Question in 1:2) {
  assign(
    x = paste0("Question",Question),
    value = lmh14[,.(ID, education_code, age, sex, item = get(paste0("question",Question)))])
}
RyanF
  • 119
  • 6
  • Thank you! not to be difficult - what can I do if i have some values called "Question1", "question1_1" and "question1_text" - can this be included in the loop? – Hellihansen Sep 01 '22 at 06:59