0

I am curious that why the following code doesn't work for adding column data to a data frame.

a <- c(1:3)
b <- c(4:6)
df <- data.frame(a,b)  # create a data frame example

add <- function(df, vector){
    df[[3]] <- vector
}                     # create a function to add column data to a data frame

d <- c(7:9)           # a new vector to be added to the data frame
add(df,d)             # execute the function

If you run the code in R, the new vector doesn't add to the data frame and no error also.

3
  • 3
    You need to return df on the line following df[[3]] <- vector then assign df <- add(df, d). It's best to never modify objects in different environments from inside a function. Commented Jul 1, 2017 at 1:56
  • Why does the df needs to be returned? And the function also doesn't modify the data frame object. Commented Jul 1, 2017 at 1:58
  • @Friday Interesting Commented Jul 1, 2017 at 2:07

1 Answer 1

1

R passes parameters to functions by value - not by reference - that means inside the function you work on a copy of the data.frame df and when returning from the function the modified data.frame "dies" and the original data.frame outside the function is still unchanged.

This is why @RichScriven proposed to store the return value of your function in the data.frame df again.

Credits go to @RichScriven please...

PS: You should use cbind ("column bind") to extend your data.frame independently of how many columns already exist and ensure unique column names:

add <- function(df, vector){
    res <- cbind(df, vector)
    names(res) <- make.names(names(res), unique = T)
    res   # return value
}

PS2: You could use a data.table instead of a data.frame which is passed by reference (not by value).

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the detailed explanation!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.