-2

I am very new to R, and also to posting on forums, but I have found other Q&A threads really useful so thought I would give it a try!

I have a variable for "% of senior management time spent dealing with government regulations". This, of course, includes numbers from 0 to 100 but also "no time was spent" and "don't know". This means it is structured as a factor.

For other variables, I have been using unfactor() followed by as.numeric() to coerce the "don't knows" into NAs and retain the underlying values. However, here I want "no time was spent" to be treated as 0, and "don't know" to be treated as NA.

Is there any way of doing this?

Edit for reproducible example

> head(Benin2016$j2)
[1] No time was spent 5                 50                1                
[5] No time was spent 20               
23 Levels: 1 10 100 12 15 2 20 25 3 30 4 40 48 5 50 6 67 70 72 80 ... No time was spent

> dput(Benin2016$j2)
structure(c(23L, 14L, 15L, 1L, 23L, 7L, 6L, 1L, 4L, 14L, 1L, 
22L, 6L, 14L, 4L, 8L, 14L, 6L, 23L, 23L, 6L, 16L, 19L, 1L, 14L, 
15L, 1L, 7L, 13L, 10L, 1L, 9L, 23L, 1L, 9L, 23L, 23L, 6L, 7L, 
19L, 23L, 6L, 1L, 6L, 14L, 1L, 4L, 20L, 14L, 1L, 23L, 1L, 6L, 
2L, 9L, 22L, 23L, 6L, 6L, 14L, 1L, 23L, 6L, 22L, 2L, 6L, 23L, 
14L, 2L, 7L, 7L, 6L, 4L, 7L, 23L, 22L, 14L, 22L, 23L, 2L, 22L, 
14L, 23L, 4L, 14L, 5L, 9L, 11L, 18L, 4L, 1L, 23L, 17L, 23L, 22L, 
6L, 22L, 2L, 9L, 1L, 23L, 22L, 2L, 22L, 6L, 14L, 1L, 22L, 2L, 
14L, 23L, 6L, 22L, 22L, 12L, 11L, 14L, 2L, 9L, 1L, 20L, 3L, 22L, 
21L, 21L, 23L, 1L, 2L, 6L, 6L, 6L, 23L, 21L, 6L, 22L, 6L, 6L, 
8L, 15L, 23L, 9L, 6L, 23L, 3L, 1L, 14L, 7L, 4L, 4L, 23L), .Label = c("1", 
"10", "100", "12", "15", "2", "20", "25", "3", "30", "4", "40", 
"48", "5", "50", "6", "67", "70", "72", "80", "90", "Don't know (spontaneous)", 
"No time was spent"), class = "factor")
Uwe Keim
  • 38,279
  • 56
  • 171
  • 280
  • 1
    Hi, and welcome to Stack Overflow! In order for us to help you, please provide a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). For example, to produce a minimal data set, you can use `head()`, `subset()`, or the indices. Then use `dput()` to give us something that can be put in R immediately. Also, please make sure you know what to do [when someone answers your question](https://stackoverflow.com/help/someone-answers). Finally, here is a link to Stack Overflow's [help center](https://stackoverflow.com/help). Thank you! – iamericfletcher Aug 09 '20 at 10:38

1 Answers1

0

Hard to say without seeing a reproducible example, but this is one way to do it:

dataframe$variable[dataframe$variable=="no time was spent"] <- 0
dataframe$variable[dataframe$variable=="don't know"] <- "NA"

Where dataframe is the name of your dataframe, and variable is the name of your variable (here % of senior management time spent dealing with government regulations, if I understood correctly).

johnjohn
  • 587
  • 7
  • 14