简体   繁体   English

在R中编写函数时传递字符串/字符参数

[英]Passing string/ character argument when writing a function in R

For example, I'm trying to write this function that converts a probability table into data.frame in R. I want the argument "na" to be the first colname of this data frame. 例如,我正在尝试编写将此函数将概率表转换为R中的data.frame的函数。我希望参数“ na”成为该数据帧的第一个列名。

  prop_table_to_df <- function(table, nm){
     data.frame(nm = factor(names(table)), Percentage = table)
  }

Suppose I call a function (sk_table, "age_group") The expected out output is this 假设我调用一个函数(sk_table,“ age_group”),预期的输出是这个

        age_group Percentage
(15,20]   (15,20]  0.4518717
(20,25]   (20,25]  0.3118461
(25,30]   (25,30]  0.2136201
(30,35]   (30,35]  0.1863965

But instead the output is 但是输出是

             nm   Percentage
(15,20]   (15,20]  0.4518717
(20,25]   (20,25]  0.3118461
(25,30]   (25,30]  0.2136201
(30,35]   (30,35]  0.1863965

How do I fix this? 我该如何解决? Apparently, in this situation, R doesn't accept string or character as an argument when wrting the function. 显然,在这种情况下,R在编写函数时不接受字符串或字符作为参数。 Thanks for helping. 感谢您的帮助。

You'll have to add another line to do the renaming after making the data.frame. 在制作data.frame之后,您必须添加另一行以进行重命名。 I've done that below, renaming the first column of the new df to the function input nm. 我在下面做了,将新df的第一列重命名为函数输入nm。

prop_table_to_df <- function(table, nm){
    df = data.frame(nm = factor(names(table)), Percentage = table)
    colnames(df)[1] = nm #rename first column to value of nm
    return(df)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM