Home > Software engineering >  replacing list key name by variable in R
replacing list key name by variable in R

Time:10-19

So let's say I want to create a list like that:

x <- c(John=23, Mary=33)

Is there a way to substitute key names with variables. Something like that (but that doesn't work for obvious reasons:

husband <- 'John'
wife <- 'Mary'
x <- c(husband=23, wife=33)
# Expected output: c(John=23, Mary=33)

In other words in the example above is there a way to replace husband with John etc.?

CodePudding user response:

You may use setNames.

husband <- 'John'
wife <- 'Mary'
setNames(c(23, 33), c(husband, wife))

# John Mary 
#  23   33 

Or with dplyr -

library(dplyr)
unlist(lst(!!husband := 23, !!wife := 33))

CodePudding user response:

In Base R:

A way that works for all names, and get's it from variable name:

names(x) <- Map(function(x) eval(parse(text=x)), names(x))

> x
John Mary 
  23   33 
> 

CodePudding user response:

We could use dput

x <- c(John=23, Mary=33)
husband <- 'John'
wife <- 'Mary'

result <- dput(x)

output:

c(John = 23, Mary = 33)
  •  Tags:  
  • r
  • Related