【问题标题】:How to use colnames() inside a function in R without it turning the numerical output into a character?如何在 R 的函数中使用 colnames() 而不将数字输出转换为字符?
【发布时间】:2020-08-22 00:30:59
【问题描述】:

我写了一个R 函数,它接受它的输入并输出一个数据帧。它可以正常工作,但是,当我尝试添加另一行来命名输出数据帧的唯一列时,它失败了。

为此,我尝试使用colnames()

操作失败的结果是character,而不是正确的数据帧。 这是一个直接涉及问题的可重现的小例子。

# 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"

【问题讨论】:

    标签: r dataframe rename


    【解决方案1】:

    我们需要返回数据集。在 OP 的函数中,它返回最后一个表达式,即将列名分配给“数字”,并且由于只有一列,因此返回了列名“数字”

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

    或者不是创建多个语句,而是单个语句

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

    【讨论】:

    • 现在速度很快。
    • 知道为什么这是必要的吗,@akrun?我错过了什么?
    • @MasonBeau 它正在评估最后一个语句或表达式,即colnames。否则你可以使用setNames(data.frame(my_input), "numbers")
    • 更简单的是data.frame(numbers = my_input)。最简单?
    • 好的,知道了,我正在考虑问题中的示例。
    【解决方案2】:

    单行:

    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
    

    【讨论】:

      猜你喜欢
      • 2013-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-15
      • 2017-05-25
      • 1970-01-01
      相关资源
      最近更新 更多