Home > OS >  How do I recode multiple variables from string to numeric?
How do I recode multiple variables from string to numeric?

Time:10-07

I am trying to recode multiple columns of data from string variables (e.g. "None of the time", "Some of the time", "Often"...) to numeric values (e.g. "None of the time" = 0). I have seen a number of different responses to similar questions but when I have tried these they seem to remove all of the data and replace it with NA.

For_Analysis <- data.frame(Q11_1=c("None of the time", "Often", "Sometimes"),
 Q11_2=c("Sometimes", "Often", "Never"), Q11_3=c("Never", "Never", "Often"))

For_Analysis <- For_Analysis%>% 
  mutate_at(c("Q11_1", "Q11_2", "Q11_3"), 
            funs(recode(., "None of the time"=1,  "Rarely"=2,
                        "Some of the time"=3, "Often"=4, "All of the time"=5)))

When I run this second bit of code I get the following output

## There were 14 warnings (use warnings() to see them)

And all of the data within the dataframe is recoded to NA instead of the numeric values I want.

CodePudding user response:

You are getting an error because there are some values which do not match. Also you can replace mutate_at with across.

library(dplyr)

For_Analysis <- For_Analysis%>% 
  mutate(across(starts_with('Q11'), ~recode(., "None of the time"=1,  "Rarely"=2,
                        "Sometimes"=3, "Often"=4, "All of the time"=5, "Never" = 1)))

For_Analysis

#  Q11_1 Q11_2 Q11_3
#1     1     3     1
#2     4     4     1
#3     3     1     4

I have taken the liberty to assume "Never" is same as "None of the time" and coded as 1.

CodePudding user response:

The following method seems to have worked for my issue (recoding string variables to numeric in multiple columns):

For_Analysis <- data.frame(Q11_1=c("Never", "Often", "Sometimes"),
 Q11_2=c("Sometimes", "Often", "Never"), Q11_3=c("Never", "Never", "Often"))

New_Values <- c(1, 2, 3, 4, 5)
Old_Values <- unique(For_Analysis$Q11_1)

For_Analysis[1:3] <- as.data.frame(sapply(For_Analysis[1:3],
                     mapvalues, from = Old_Values, to = New_Values))

Thanks for the help!

CodePudding user response:

The easiest way to convert it to a variable of type factor and then to numeric.

library(tidyverse)

For_Analysis <- data.frame(Q11_1=c("None of the time", "Often", "Sometimes"),
                           Q11_2=c("Sometimes", "Often", "Never"), Q11_3=c("Never", "Never", "Often"))

fRecode = function(x) x %>% fct_inorder() %>% as.numeric()
For_Analysis %>% mutate_all(fRecode)

output

  Q11_1 Q11_2 Q11_3
1     1     1     1
2     2     2     1
3     3     3     2
  • Related