Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Change character values under specific columns that ends with similar suffixes in R

Hello friends I have a data frame like this:

# Define the column names
col_names <- c("A_1C_1", "B_1C_1", "C_1C_1", "D_1C_1", "E_1C_1", "F_1C_1", "G_1C_1", "H_1E_1", "I_1D_1", "J_1D_1")

# Define the data frame
df <- data.frame(replicate(10, sample(c("apple", "banana", "kiwi", "milk"), 10, replace = TRUE)),
                 stringsAsFactors = FALSE)
# Set the column names
colnames(df) <- col_names
df
    A_1C_1 B_1C_1 C_1C_1 D_1C_1 E_1C_1 F_1C_1 G_1C_1 H_1E_1 I_1D_1 J_1D_1
1    milk   kiwi   kiwi banana banana   kiwi banana   kiwi banana   kiwi
2    milk banana banana   milk banana banana   milk banana  apple   kiwi
3    milk banana banana   kiwi banana banana banana banana banana banana
4    milk   kiwi  apple banana   kiwi banana   kiwi   kiwi banana   milk
5    milk  apple   kiwi banana banana banana banana banana   milk   milk
6    kiwi banana banana  apple   kiwi banana   kiwi   kiwi banana   milk
7    kiwi  apple  apple   milk   milk banana   milk   milk   kiwi banana
8  banana   kiwi   kiwi   milk  apple  apple   milk  apple  apple   milk
9    milk  apple   kiwi   milk   milk banana   milk   kiwi   kiwi   milk
10   milk   kiwi  apple   milk banana   kiwi banana   kiwi   milk banana

What I want to do is to change character values under the columns that end with C_1 in a way that apple will be sweet-sour,
banana will be sweet,
kiwi will be sour and
milk will turn to tasteless.

how can I do that?
Thanks a lot!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use across inside mutate to apply a function (.fns) across multiple variables, given the condition you want (.cols).

library(dplyr)

df %>% 
  mutate(
    across(
      .cols = ends_with("C_1"),
      .fns = ~case_when(
        . == "apple" ~ "sweet sour",
        . == "banana" ~ "sweet",
        . == "kiwi" ~ "sour",
        . == "milk" ~ "tasteless"
      )
    )
  )
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading