简体   繁体   中英

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.

  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

        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. Thanks for helping.

You'll have to add another line to do the renaming after making the data.frame. I've done that below, renaming the first column of the new df to the function 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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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