Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (50.2k points)

I am having a dataframe and in the column named "roles", each row has a value of "students" or "teacher". I want to substitute these values with "st" or "te" respectively.

roles_complete <- c("students","teacher")

roles_standard <- c("st", "te")

data$roles <- stri_replace_all(data$roles, regex= roles_complete, roles_standard)

The above code is doing something, but I want all the values to get replaced. How can I do that?

    roles

1   st

2   students

3   teacher

4   te

5   st

6   students

7   teacher

8   te

9   st

10  students

11  teacher

12  te

1 Answer

0 votes
by (107k points)

I think you can use the function str_replace_all() in the R programming for replacing the matched patterns. The syntax is:

library(stringr)

data <- c("students", "teacher", "students", "teacher")

str_replace_all(data, c("students" = "st", "teacher" = "te"))

Thus, for your case, the code will be:

data$roles <- str_replace_all(data$roles, c("students" = "st", "teacher" = "te"))

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...