Creating a Categorical Variable from a quantitative one

I am having trouble with where to start with organizing and analyzing my data. I have a variable called stai_score which is the level of anxiety for subjects. This score is numerical ranging from 20-80 and is recorded at 3 time points (baseline, week 4 and week 8). I am trying to create a new variable called change. This variable is a categorical variable that measures a success as "a change in stai_score greater than or equal to 3 from baseline to week 8" and a failure as "a change in stai_score less than 3 from baseline to week 8".

I am struggling in how to put in code that will create this new vector "change" because of the two timepoints. Any ideas?

1 Like

Hi!

To help us help you, could you please prepare a reproducible example (reprex) illustrating your issue? Please have a look at this guide, to see how to create one:

Hi, and welcome!

Please see the FAQ: What's a reproducible example (`reprex`) and how do I do one? Using a reprex, complete with representative data will attract quicker and more answers. This question is not complex enough to require one, though.

suppressPackageStartupMessages(library(dplyr))
dat <- structure(list(
  recid =
    c(1, 2, 3),
  obs =
    c(0, 4, 8),
  subj =
    c(1, 1, 1),
  score =
    c(20, 40, 60)
),
class =
  c("spec_tbl_df", "tbl_df", "tbl", "data.frame"),
row.names =
  c(NA, -3L), spec = structure(list(cols = list(recid = structure(list(),
  class =
    c("collector_double", "collector")
), obs = structure(list(),
  class =
    c("collector_double", "collector")
), subj = structure(list(),
  class =
    c("collector_double", "collector")
), score = structure(list(),
  class =
    c("collector_double", "collector")
)), default = structure(list(),
  class =
    c("collector_guess", "collector")
), skip = 1),
class = "col_spec"
)
)

dat
#> # A tibble: 3 x 4
#>   recid   obs  subj score
#>   <dbl> <dbl> <dbl> <dbl>
#> 1     1     0     1    20
#> 2     2     4     1    40
#> 3     3     8     1    60

dat %>%
  dplyr::mutate(change = ifelse(score > lag(score, 2), "success", "failure")) %>%
  filter(obs == 8)
#> # A tibble: 1 x 5
#>   recid   obs  subj score change 
#>   <dbl> <dbl> <dbl> <dbl> <chr>  
#> 1     3     8     1    60 success

Created on 2020-03-28 by the reprex package (v0.3.0)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.