Home > Net >  Output an altered list given a list in R
Output an altered list given a list in R

Time:09-21

I have a list like so:

animals = c('dog','cat','mouse')

Is there a way given the animals list to generate the this list: c('dog' = 'Dog', 'cat' = 'Cat', 'mouse' = 'Mouse')?

CodePudding user response:

We may use str_to_title

library(stringr)
setNames(str_to_title(animals), animals)

-output

  dog     cat   mouse 
  "Dog"   "Cat" "Mouse" 

Or use sub

setNames(sub("(.)", "\\U\\1", animals, perl = TRUE), animals)

or may also do

setNames({`<-`(substr(animals, 1, 1), toupper(substr(animals, 1, 1))); animals}, animals)
    dog     cat   mouse 
  "Dog"   "Cat" "Mouse" 

CodePudding user response:

Also you can use tools::toTitleCase()

tools::toTitleCase(animals)
#[1] "Dog"   "Cat"   "Mouse"

or

setNames(tools::toTitleCase(animals), animals)
#---
    dog     cat   mouse 
  "Dog"   "Cat" "Mouse"
  •  Tags:  
  • r
  • Related