-3

New to R - I think there should be a simple solution to this, but I'm having trouble getting it right.

I have results from a questionnaire in the form of 18 variables (each corresponds with a questionnaire item) that I want to score. Results for each variable are either "True", "Sometimes", or "Not true" (all characters). I want to create a loop which changes all 18 variables to numeric scores of 2, 1, and 0, respectively, so I can score the questionnaire.

Could anyone suggest a way of doing this? Thanks!

Sarah
  • 3
  • 1
  • Can you provide your data in `dput(my_data)` form? – acylam Aug 21 '18 at 13:56
  • You can apply to each one of your columns a recoding process. Some more info here: https://stackoverflow.com/questions/16179114/using-car-to-recode-across-range-of-columns – AntoniosK Aug 21 '18 at 13:58
  • 1
    Possible duplicate of [Using \`car\` to recode across range of columns](https://stackoverflow.com/questions/16179114/using-car-to-recode-across-range-of-columns) – divibisan Aug 21 '18 at 18:09

3 Answers3

0

You can use the ifelse construct like this:

df$Ques1_Score <- ifelse(df$Ques1 == "True", 2, ifelse(df$Ques1 == "Sometimes", 1, 0))
SmitM
  • 1,366
  • 1
  • 8
  • 14
0

If you data.frame is called d and contains a column results you could do the following

d$results <- match(d$results, c("Not true", "Sometimes", "True")) - 1
Teun
  • 579
  • 1
  • 7
  • 14
0

Another solution with dplyr, and if you don't care about the values (you could always substract 1, and get 0-1-2:

require(dyplr)

dat <- tibble(
  v1 = factor(c("a", "b", "c")),
  v2 = factor(c("a", "b","a"))
) # create some simulated data

# A tibble: 3 x 2
  v1    v2   
  <fct> <fct>
1 a     a    
2 b     b    
3 c     a   

trasform every factor in numeric (this will work without explicity naming all variables):

dat %>% mutate_if(is.factor, as.numeric) # trasforms factor in numeric

# A tibble: 3 x 2
     v1    v2
  <dbl> <dbl>
1     1     1
2     2     2
3     3     1
RLave
  • 8,144
  • 3
  • 21
  • 37