Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在R中编写函数时传递字符串/字符参数_R_String_Function_Character - Fatal编程技术网

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

在R中编写函数时传递字符串/字符参数,r,string,function,character,R,String,Function,Character,例如,我试图编写一个函数,将概率表转换为R中的data.frame。我希望参数“na”是这个数据帧的第一个colname prop_table_to_df <- function(table, nm){ data.frame(nm = factor(names(table)), Percentage = table) } 但结果是 nm Percentage (15,20] (15,20] 0.4518717 (20,25] (2

例如,我试图编写一个函数,将概率表转换为R中的data.frame。我希望参数“na”是这个数据帧的第一个colname

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

             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

我该如何解决这个问题?显然,在这种情况下,R在编写函数时不接受字符串或字符作为参数。谢谢你的帮助

在创建data.frame之后,您必须添加另一行来进行重命名。我已经在下面完成了,将新df的第一列重命名为函数input 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)
}

prop_table_to_df您可以尝试使用
setnames
:例如
setnames(data.frame(factor(name(table)),table),c(“age_group”,“Percentage”)
,其中“age_group”是传递给函数的字符串。@symbolxau
setnames
是data.table。基础是
setNames
set\u names
是matrittr/purrr.@alistaire-是的,你说得对-我每天都使用
数据。table
对我来说,它算作基数:~)这正是我所做的!非常感谢。我只是想知道是否有一种更直接的方式来编写它而不需要数据。表方式。
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)
}