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"