1

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.

Inho Lee
  • 127
  • 1
  • 12
  • 3
    Try `y <- myFunction(x)`. – Park Dec 16 '21 at 00:17
  • @Park OMG! It is so simple way. Thanks a lot!!! :D – Inho Lee Dec 16 '21 at 00:26
  • 1
    You have a lot of unnecessary code too, this does the same: `myFunction <- function(x) {rename(x, "newX1" = "X1", "newX2" = "X2")}` and arguably, it shouldn't even be a custom function, you could just use `y <- rename(...` – rg255 Dec 16 '21 at 05:57
  • To elaborate on Park's answer: R uses "call by value". This means that input arguments are copied and changing them in the function body has no effect on the passed variable. – cdalitz Dec 16 '21 at 12:10
  • @rg255 When I do data cleansing, I thought that function because the data have many columns that need rename process. Then I can use the function by putting each filename in x. If you have a better idea, please let me know. Thank you for your answer. – Inho Lee Dec 17 '21 at 06:16
  • you mean you have a lot of data.frames where you want to do the same renaming? e.g. `df1 <- rename(df1, "newX" = "x", "newY" = "y"); df2 <- rename(df2, "newX" = "x", "newY" = "y"); df3 <- rename(df3, "newX" = "x", "newY" = "y"); ...` – rg255 Dec 17 '21 at 07:58
  • @rg255 Oh, I misunderstood your first comment. I could not recognize the `{ }` part in your comment. – Inho Lee Dec 18 '21 at 19:13

1 Answers1

1

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"))
}
rg255
  • 4,119
  • 3
  • 22
  • 40