Hey,
I am new to R and need some help.
I want to recode categorical variable. I want category 1 and 2 to be in one category 0 with a name "no access", similarly category 3, 4, and 5 to be 1 with a name "with access". Other categories should be NA. Here is the code I have in Stata:
q6001 (1/2=0 "No access")(3/5=1 "With access")(6/max=.), gen(q6001BR)
In R there is no label attribute for factors (categorical variables) labels get converted to levels (categories), so you may want to just use your labels as levels like this.
library(car)
x <- as.factor(c(1, 2, 3, 4, 5, 6, 7))
recode(x, "1:2='no access';3:5='with access';else=NA")
#> [1] no access no access with access with access with access <NA>
#> [7] <NA>
#> Levels: no access with access
I need to change it to 0 and 1 so that its structure also changes to 0 and 1
Later on I need to change the variable(Q6001BR) to numeric to rowSum it with other similar variables. With above problem the sum results in summing the values as shown by the str() function.
We don't really have enough info to help you out. Could you ask this with a minimal REPRoducible EXample (reprex)? A reprex makes it much easier for others to understand your issue and figure out how to help.
Maybe a walk around solution would be to use a boolean variable (TRUE/FALSE = 1/0) instead of a factor that way you can use rowsum directly.