what I'm trying here is to build a function that I could run every time that I want to replace the reporting values in a dataset with their actual answer options.
Hypothetically, I the following answer options used to describe cars' colour:
answer_options <- c("blue", "red", "yellow", "green")
and then a dataset that contains the colour column:
data <- data.frame(Animal=c("Parrot", "Pigeon", "Crocodile", "Impala", "Dolphin", "Dinosaur"), Colour=c(0,1,1,2,1,3), Year=c(2018, 2017, 2018, 2019, 2020, 2024))
I have looked into every relevant question in here but can't find a way to make the following function replace the reporting values with the corresponding answer_options (Please note that I could replace them alternatively but my mission is to build a function and not have to repeat blocks of code every time):
answer.option.replacer <- function(dataset, column_index, replacer_vector, replacer_length){
for (i in 0:replacer_length){
dataset[[column_index]][dataset[[column_index]]==i] <-replacer_vector[i+1]}
return(dataset[[column_index]])
}
Now if I run:
answer.option.replacer(data, 2, answer_options, 4)
It prints the wished column with the values replaced but it doesn't actually replace them in the data. Any help would be really appreciated since I'm not very experienced with functions.