[Solved] Shifting strings in R


Data

library (dplyr)
df <- data.frame(
        x = c("head", "hand", "key"),
        y = c("car", "nose", "house"),
        z = c("toe", "mouse", "ball"),
        stringsAsFactors = FALSE
    )

Code

# Add new column.
df_result <- df %>%
    mutate(
        new = case_when(
            x %in% c("head", "hand") ~ x,
            z == "ball" ~ z,
            TRUE ~ NA_character_
        )
    )
# Remove old values.
df_result$x[df_result$x %in% c("head", "hand")] <- NA_character_
df_result$z[df_result$z == "ball"] <- NA_character_

Result

> df_result
     x     y     z  new
1 <NA>   car   toe head
2 <NA>  nose mouse hand
3  key house  <NA> ball

Caveat: This approach prioritizes a “hand” or “head” in x before a “ball” in z.

solved Shifting strings in R