Home > other >  How to store the output of my customized function in R?
How to store the output of my customized function in R?

Time:12-19

I want to build my function to change the column name.

x1 = c(1:5)
x2 = c(6:10)
x = data.frame(
  X1 = x1,
  X2 = x2
)

myFunction = function(x) {
  x <- rename(x, "newX1" = "X1")
  x <- rename(x, "newX2" = "X2")
  newX <- x
  return(newX)
}

print(myFunction(x))

output is below:

  newX1 newX2
1     1     6
2     2     7
3     3     8
4     4     9
5     5    10

I can see the result that I intended, but the output does not store as data in my memory. I want to do the next process using the output (data) of the function.

Thank you.

CodePudding user response:

There is a lot of code that you do not need in your attempt - essentially you have just created a wrapper for the rename() function without adding much to it. You could just do

rename(x, "newX1" = "x1", "newX2" = "x2"))

To get it to assign ot the object, you can then do

x <- rename(x, "newX1" = "x1", "newX2" = "x2"))

Or

assign("x", rename(x, "newX1" = "x1", "newX2" = "x2"))

From your comments, it seems you have many data.frames where you want to do this same renaming, you could automate that with a for loop

# Exmaple datasets
df1 <- df2 <- df3 <- df4 <- df5 <- data.frame(x1 = 1:5, x2 = 6:10)
# Define datasets to rename
datasets_to_rename <- c("df1", "df2", "df3")
# Rename the selected datasets
for(i in datasets_to_rename){
  assign(i, rename(get(i), "newX1" = "x1", "newX2" = "x2"))
}

You could make this more automatic if you want to do this for all data.frames in the global environment with

for(i in names(Filter(is.data.frame, as.list(.GlobalEnv)))){
  assign(i, rename(get(i), "newX1" = "x1", "newX2" = "x2"))
}
  • Related