How to use colnames() inside a function in R without it turning the numerical output into a character?

Viewed 102

I wrote an R function that takes its input and outputs a dataframe. It worked as it should, however, when I tried to add another line to name the only column of the output dataframe, it failed.

For this, I tried to use colnames().

The result of the failed operation is a character instead of the correct dataframe. Here's a little reproducible example that goes straight into the issue.

# Fake Data

numbers = rnorm(5)

# Functions ---------------------------------------------------------------

# Dataframe is generated correctly. 

print_df_right = function(my_input){
   number_df = data.frame(my_input)
}

foo = print_df_right(numbers)
foo # A correct, column-nameless dataframe
#>     my_input
#> 1  0.3379014
#> 2  0.5306519
#> 3  0.7689149
#> 4 -0.5548860
#> 5 -2.1199438


# Dataframe is ruined because colnames() turns it into a vector.
ruin_my_df = function(my_input){
   number_df = data.frame(my_input)
   colnames(number_df) = c("numbers")
}

foo = ruin_my_df(numbers)
foo # This was supposed to be a dataframe, but instead is a character.
#> [1] "numbers"
2 Answers

We need to return the dataset. In the OP's function, it is returning the last expression i.e. assigning the column names to 'numbers' and as there is only one column, the column name 'numbers' got returned

ruin_my_df_corrected <- function(my_input){
   number_df <- data.frame(my_input)
   colnames(number_df) <- c("numbers")
   number_df
   }

Or instead of creating multiple statements, it can be a single one

ruin_my_df_corrected <- function(my_input){
        setNames(data.frame(my_input), "numbers")

  }

A one-liner:

names_right_df <- function(my_input) data.frame(numbers = my_input)

names_right_df(numbers)
#     numbers
#1 -0.7654521
#2  1.0077708
#3  1.1608095
#4  1.1352666
#5 -1.0030617
Related