Home > Mobile >  Trying to change character variable across multiple columns
Trying to change character variable across multiple columns

Time:12-22

(I'm like super new to R) Trying to change "si" to "yes" .

I want to get from here:

survey_done

column_a column_b
Si         Yes
Si         Si
Yes        No
No         No
No         Si

to here:

column_a column_b
Yes        Yes
Yes        Yes
Yes        No
No         No
No         Yes

I've tried this formula

survey_done <-survey_done %%
  recode(across(c(column_a,
                  column_b), "Sí" = "Yes"))

but I get an error:

Error in `across()`:
! Must be used inside dplyr verbs.
Run `rlang::last_error()` to see where the error occurred.

How can i correct this error. Also is there another formula that allows me to specify the columns?

CodePudding user response:

The recode should be within across as the input .x should be a vector (from ?recode). We loop across the columns of inerest in mutate and then apply the recode to modify the values in the column

library(dplyr)
survey_done <- survey_done %>% 
   mutate(across(c(column_a, column_b), 
       ~ recode(.x,  "Si" = "Yes")))

-output

survey_done
 column_a column_b
1      Yes      Yes
2      Yes      Yes
3      Yes       No
4       No       No
5       No      Yes

In base R, we could do

survey_done[survey_done == "Si"] <- "Yes"

data

survey_done <- structure(list(column_a = c("Si", "Si", "Yes", "No",
 "No"), column_b = c("Yes", 
"Si", "No", "No", "Si")), class = "data.frame", row.names = c(NA, 
-5L))

CodePudding user response:

Another approach using replace

replace(survey_done, survey_done == "Si", "Yes")
  column_a column_b
1      Yes      Yes
2      Yes      Yes
3      Yes       No
4       No       No
5       No      Yes

The tidy way

library(dplyr)

survey_done %>% 
  mutate(replace(across(1:2), across(1:2) == "Si", "Yes"))
  column_a column_b
1      Yes      Yes
2      Yes      Yes
3      Yes       No
4       No       No
5       No      Yes
  • Related