Home > database >  Pass a function input as column name to data.frame function
Pass a function input as column name to data.frame function

Time:02-05

I have a function taking a character input. Within the function, I want to use the data.frame() function. Within the data.frame() function, one column name should be the function's character input.

I tried it like this and it didn't work:

frame_create <- function(data, **character_input**){

...
some_vector <- c(1:50)

temp_frame <- data.frame(**character_input** = some_vector, ...)

return(temp_frame)

}

CodePudding user response:

Either use, names to assign or with setNames as = wouldn't allow evaluation on the lhs of =. In package functions i.e tibble or lst, it can be created with := and !!

frame_create <- function(data, character_input){
    some_vector <- 1:50
    temp_frame <- data.frame(some_vector)
    names(temp_frame) <- character_input
    return(temp_frame)
}

CodePudding user response:

Can you explain your requirement for using a function to create a new dataframe column? If you have a dataframe df and you want to make a copy with a new column appended then the trivial solution is:

df2 <- df
df2$new_col <- 1:50

Example of merging multiple dataframes in R:

cars1 <- mtcars
cars2 <- cars1
cars3 <- cars2

list1 <- list(cars1, cars2, cars3)

all_cars <- Reduce(rbind, list1)
  • Related