I'm an R newbie. I wish to recode the high range of a vector of numeric values to a maximum numeric value. Here is a simplified example:
x <- c(25, 21 , 0 , 29 , 34 , 66 , 77)
I would like all of the values over 30 to be recoded to 30, with the others copied. I realize this is a very simple question but I've been struggling to find an answer. I've consulted documentation for recode and mutate, but haven't gotten any code to work. Thanks for your help.
one way to do this
x <- c(25, 21 , 0 , 29 , 34 , 66 , 77)
x <- ifelse(x > 30, 30, x)
for more complex statements you could use case_when()
which is especially useful in mutate()
(both from the tidyverse dplyr package).
Thank you, that worked for my example. I also created a 2-vector dataframe, on which it also worked. It is not working on my bigger, more complex dataset, a file that was imported from Stata to R through the Haven package. (There's lots of other R code that is working.) The R data file is described as a data.frame, with the variable "haven_labelled". I'm afraid I can't share that dataset. The error message is "object is not found". But it's surely there. So I wonder if it is a problem with the origin of the file or the way I'm referring to the variable. I'm going back to Stata to create a simpler file for import to try to narrow down the problem, maybe suppress the labels. If you have any other suggestions, would be great to hear.
Good that this worked for this example. I doubt that you get this error message because of the file's origin (or the labels). If this variable really exists in your data frame, I guess it must be your second idea: the way you are referring to the variable.
To be able to help you answer your question, I would need a minimal reproducible example. "The goal of a reprex is to package your code, and information about your problem so that others can run it and feel your pain. Then, hopefully, folks can more easily provide a solution." (FAQ: What's a reproducible example (reprex
) and how do I do one?)
Just to close the loop, I came back to this and, with the help of a clear presentation of ifelse with mutate, wrote code that worked. The presentation is here. I'm not sure what crud was in my previous code. Thanks again for responding.
This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.