0

I want to add a new row to an existing data frame, using a function like this:

df <- data.frame(num1 = numeric(),
                 num2 = numeric(),
                 int1 = integer(),
                 chr1 = character(),
                 stringsAsFactors=FALSE)

filler <- function () {
  newrow = c(0.1, 0.01, 100, "char")
  df[nrow(df)+1, ] <- newrow
  assign(x = "df", value = df, envir = .GlobalEnv)
}
filler

but nothing is happening.

I'd like to get the following output:

> df
  num1 num2 int1 chr1
1  0.1 0.01  100 char

Note: I don't want to define the new table within a function, because I want to rerun the function afterwards with different "newrow" values.

3
  • This line will coerce all values to character BTW: c(0.1, 0.01, 100, "char"). Commented Apr 12, 2016 at 20:38
  • 1
    You should pass df into the function and return the modified data frame to have the function fit into the functional programming paradigm. Or have the function not touch the data frame and just return a 1-line data frame of the row to add. In either case, just use rbind() inside the function or out of it. Commented Apr 12, 2016 at 20:43
  • @Gregor - your solution worked fine. Thanks! :) Commented Apr 12, 2016 at 21:05

1 Answer 1

2

I believe this should do the trick for you. I used a generic a row so you can pass new values to the data frame. You can pass a vector of values by doing the following: c(value1, value2, value3, value4)

df <- data.frame(num1 = numeric(),
                 num2 = numeric(),
                 int1 = integer(),
                 chr1 = character(),
                 stringsAsFactors=FALSE)

row_attempt <- c(1,2,3,"Master")

filler <- function(frame_to_attach, my_row){
    newrow = my_row
    data_frame <- rbind(frame_to_attach,my_row)
    colnames(data_frame) <- colnames(frame_to_attach)
   return(data_frame)
}

z <- filler(df, row_attempt)
z
Sign up to request clarification or add additional context in comments.

1 Comment

@sandoronodi You are just not assigning the result; this answer works just fine. df <- filler(df, row_attempt) now I have one row, df <- filler(df, row_attempt) now two, run it as many times as you like, just assign use df <- to assign the output each time.

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.