简体   繁体   中英

How to rename objects in R based on function arguments?

Let's say I have a function which returns a vector based on some dataframe argument. I want to use this function iteratively in a loop, so I want the vectors it returns to have different names (otherwise I would not be able to distinguish them). Specifically, the name of the returned vector needs to change based on some index, which I pass to the function as an argument, t. So, if I call the function with the argument t=1, it returns a vector called (for example) "vector1"; if I call the function with the argument t=2, it returns a vector called "vector2," and so on. Note that for the purposes of this question it doesn't really matter what the elements of the vectors are; they can be all the same or all different--I just want to rename them based on an argument to the function.

I'm new to R so sorry if this question is asked inappropriately. Below is what I have tried, which is obviously wrong, but hopefully illustrates what I am trying to do.

#this function is passed a dataframe and returns some vector named ["vector" + the argument t] 

indexed_vector <- function(data, t) { 

   # ... code which creates a vector (called "vector") from data...#

   paste0("vector", as.character(t)) <- vector

   return(paste0("vector", as.character(t)))


}

#using the function once 
indexed_vector(data, 10)
#ideally this would return a vector called "vector10"  


#using the function in a loop to create multiple vectors
for(i in 1:10){indexed_vector(data, i))
#ideally this would create a list of vectors where each is called "vectori", 
#i.e. "vector1", "vector2", "vector3"..."vector10"

Thanks!

In R, you can't return a vector called something. If you want a vector called vector_1 to just appear after you call the function without having to store it anywhere, you need to use assign or the <<- operator inside the function. This usually isn't a good idea.

However, it is a good idea to have named vectors inside a list, and this can be done simply without using a loop at all:

indexed_vector <- function(df, i) setNames(as.list(df[i]), paste0("vector_", i))

df <- data.frame(a = 1:3, b = 4:6, c = 7:9, d = 10:12)

indexed_vector(df, 1:3)
#> $vector_1
#> [1] 1 2 3
#> 
#> $vector_2
#> [1] 4 5 6
#> 
#> $vector_3
#> [1] 7 8 9

Created on 2020-06-11 by the reprex package (v0.3.0)

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