简体   繁体   中英

How to rename list objects in self defined function?

quote <- function(namefoo, namebar){
  set.seed(3)
  foo <- rnorm(n = 5)
  bar <- rnorm(n = 5)
  return(list(namefoo=foo,namebar=bar))
}

From the above function, If I ran quote(test, test1) the name of the two objects in the list remain as namefoo and namebar instead of what I specified in the function call.

If I just ran the code seperately as:

set.seed(3)
foo <- rnorm(n = 5)
bar <- rnorm(n = 5)
obj <- list(test=foo,test1=bar)

Then obj will return foo and bar with the amended names. How do I make my function do this? I've tried several combinations of including quotes as well, from the function call to the function itself but it doesn't seem to work.

One way is this:

quote <- function(namefoo, namebar){
  set.seed(3)
  foo <- rnorm(n = 5)
  bar <- rnorm(n = 5)
  out <- list(foo, bar)
  names(out) <- c(namefoo, namebar)
  out
}

You can save the list to a variable and then name the elements with names .

# quote('foo', 'bar')
# $namefoo
# [1] -0.9619334 -0.2925257  0.2587882 -1.1521319
# [5]  0.1957828
# 
# $namebar
# [1]  0.03012394  0.08541773  1.11661021
# [4] -1.21885742  1.26736872

It's a very bad idea to name your function quote , a very important R function is named just like that.

Use setNames :

fun <- function(namefoo, namebar){
  set.seed(3)
  foo <- rnorm(n = 5)
  bar <- rnorm(n = 5)
  setNames(list(foo,bar),c(namefoo, namebar))
}

fun("hi","there")
# $hi
# [1] -0.9619334 -0.2925257  0.2587882 -1.1521319  0.1957828
# 
# $there
# [1]  0.03012394  0.08541773  1.11661021 -1.21885742  1.26736872

You might also see this kind of code around too, using more advanced features of rlang / tidyverse :

library(tidyverse)
fun2 <- function(namefoo, namebar){
  set.seed(3)
  foo <- rnorm(n = 5)
  bar <- rnorm(n = 5)
  lst(!!namefoo := foo,!!namebar := bar)
}

fun2("hi","there")
# $hi
# [1] -0.9619334 -0.2925257  0.2587882 -1.1521319  0.1957828
# 
# $there
# [1]  0.03012394  0.08541773  1.11661021 -1.21885742  1.26736872

We can do

quotefn <- function(...) {
        nm <- c(...)
        out <- replicate(length(nm), rnorm(n = 5), simplify = FALSE)
        names(out) <- nm
        out}
quotefn("foo", "bar")
#$foo
#[1] -0.5784837 -0.9423007 -0.2037282 -1.6664748 -0.4844551

#$bar
#[1] -0.74107266  1.16061578  1.01206712 -0.07207847 -1.13678230

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM