A plurality of answer items separated by spaces are made into dummy variables.

Asked 2 years ago, Updated 2 years ago, 49 views

#Creating data frames
q1<-c("1", "3", "2", "4", "5")
q2<-c("12", "112", "211", "121112", "31213")
q3<-c ("1 2 3 4 5", "2 12 13", "*", "11 12", "1 2 3 4 5 6 7 8 9 10 11 12 13")
q4<-c("5", "4", "3", "2", "*")
a<-data.frame (Q1=q1, Q2=q2, Q3=q3, Q4=q4)

The above data frame read by the mark card.Only Q2 and Q3 are multi-answer items with elements separated by spaces.

As a result, I want to create a dummy variable of 0 or 1 such as "Q2_1", "Q2_2....Q3_12, Q3_13, but it doesn't work...

(I used separate and made ummies)

r

2022-09-30 16:16

1 Answers

Below is an example implementation, but I don't know how to handle '*', so I left it as it is.

make_answer_table<-function(q,tag){
  x<-as.numeric(unlist(strsplit(q[q!='*'], ""))))
  vmin<-min(x);vmax<-max(x)
  setNames(data.frame(t(sapply(q, function(item){
    if(item=='*')return(rep('*', vmax-vmin+1))
    x<-as.numeric(unlist(strsplit(item, ""))))
    sapply(vmin:vmax, function(i){ifelse(i%in%x,10)})
  }), row.names=1:length(q), c(paste(tag, vmin:vmax, sep='_')
}

q1<-c("1", "3", "2", "4", "5")
q2<-c("12", "112", "211", "121112", "31213")
q3<-c ("1 2 3 4 5", "2 12 13", "*", "11 12", "1 2 3 4 5 6 7 8 9 10 11 12 13")
q4<-c("5", "4", "3", "2", "*")

a<-cbind(
  Q1 = q1,
  make_answer_table(q2, "Q2"),
  make_answer_table(q3, "Q3"),
  Q4 = q4
)


2022-09-30 16:16

If you have any answers or tips


© 2025 OneMinuteCode. All rights reserved.