Jeremy K.
Jeremy K.

Reputation: 1792

`stringr::str_replace()` for a list or replacements--but only return one output

I have some data in chr format that looks like this (it is a multi-line chr variable):

#> cyl      10
#> disp     20

[Code for entering the data at the end of the question]

I would like to replace the variable names (eg cyl, disp) with fuller descriptions:

var_labels <- list(
                  cyl =  "Number of Cylinders",
                  disp = "Displacement")

My desired output would be:

#> Number of Cylinders      10
#> Displacement     20

What's the easiest way to do this in the tidyverse?

I've tried using purrr::map2() and stringr::str_replace(), to iterate through all of the variables and their names, but I haven't quite gotten this right. I think part of my problem is that I don't want many list items to result from the map2(), I want map2() to keep iterating on the same output then return only one result after all of the str_replace() have been made.

Or perhaps there's an easier, completely different way to accomplish the whole thing?

My attempt is:

label_vars <- function(var, var_name){
  str_replace(output, var, var_name)
}

map2(names(var_labels), var_labels, label_vars)

which returns a new output for each str_replace(), whereas I just want one output with all replacements made:

# [[1]]
# [1] "Number of Cylinders      10\ndisp     20"
# 
# [[2]]
# [1] "cyl      10\nDisplacement     20"

Code for entering in the data:

output <-"cyl      10
disp     20"
cat(output)

Upvotes: 1

Views: 645

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389175

Use a named vector instead of named list :

var_labels <- c(cyl =  "Number of Cylinders", disp = "Displacement")

Also you don't need map here since str_replace_all is vectorized :

cat(stringr::str_replace_all(output, var_labels))

#Number of Cylinders      10
#Displacement     20

Upvotes: 1

Related Questions