如何将参数发送到R中的transform函数

时间:2015-03-28 13:01:55

标签: r

我正在尝试创建以下功能:

mysplit_col <- function(df, colname, sepstr=':', 
                       firstname='part1', secondname='part2'){
    df_split<- strsplit(as.character(df[,colname]), split=sepstr)
    transform(df, firstname= sapply(df_split, "[[", 1),secondname= sapply(df_split, "[[", 2))
}

> mydf
  name position
1  HLA   1:1-15
2  HLA   1:2-16
3  HLA   1:3-17

> dput(mydf)
structure(list(name = structure(c(1L, 1L, 1L), .Label = "HLA", class = "factor"), 
    position = structure(1:3, .Label = c("1:1-15", "1:2-16", 
    "1:3-17"), class = "factor")), .Names = c("name", "position"
), class = "data.frame", row.names = c("1", "2", "3"))

> mysplit_col_(mydf, 'position')
  name position firstname secondname
1  HLA   1:1-15         1       1-15
2  HLA   1:2-16         1       2-16
3  HLA   1:3-17         1       3-17

但是在输出中,新列被命名为&#39; firstname&#39;和&#39; secondname&#39;而不是&#39; part1&#39;和&#39; part2&#39;

示例数据来自:https://stats.stackexchange.com/questions/6806/splitting-a-numeric-column-for-a-dataframe

如何更正此问题?谢谢你的帮助。

0 个答案:

没有答案