Vons
Vons

Reputation: 3335

Append column name to the beginning of values separated by an underscore

How do you append the column name to the start of each value in the column, separated by a "_", skipping the first column (or, equivalently, choosing the second and third columns)?

multiple=data.frame(id=c(1:6), 
     status=c("good", "bad", "ok", "ok", "good", "bad"), 
     breakfast=c("eggs", "sausage", "eggs", "sausage", "sausage", "eggs"))
# Desired:
#id status breakfast
#1  status_good breakfast_eggs
#2  status_bad  breakfast_sausage
#3  status_ok   breakfast_eggs
#4  status_ok   breakfast_sausage
#5  status_good breakfast_sausage
#6  status_bad  breakfast_eggs

Upvotes: 2

Views: 264

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 389155

In base R, we can use Map :

multiple[-1] <- Map(function(x, y) paste(x, y, sep = '_'), 
                     names(multiple)[-1], multiple[-1])

Or with purrr's imap_dfc :

multiple[-1] <- purrr::imap_dfc(multiple[-1], ~paste(.y, .x, sep = '_'))
multiple

#  id      status         breakfast
#1  1 status_good    breakfast_eggs
#2  2  status_bad breakfast_sausage
#3  3   status_ok    breakfast_eggs
#4  4   status_ok breakfast_sausage
#5  5 status_good breakfast_sausage
#6  6  status_bad    breakfast_eggs

Upvotes: 1

akrun
akrun

Reputation: 887541

Here is an option with tidyverse, where we loop across the columns and paste with the corresponding column name (cur_column())

library(dplyr)
library(stringr)
multiple %>%
    mutate(across(c(status, breakfast), ~ str_c(cur_column(), "_", .)))

-output

#  id      status         breakfast
#1  1 status_good    breakfast_eggs
#2  2  status_bad breakfast_sausage
#3  3   status_ok    breakfast_eggs
#4  4   status_ok breakfast_sausage
#5  5 status_good breakfast_sausage
#6  6  status_bad    breakfast_eggs

Upvotes: 2

Related Questions