具有单个参数的R函数以类似的词干重命名/合并变量

时间:2018-10-10 10:46:57

标签: r function dataframe arguments parameter-passing

作为一个偶然的R程序员,我对如何完成编程风格的任务了解不多,这些任务要在我想使用等效的shell $variables或SAS &macroparameters时进行。 (我不确定R中是否存在?)

我正在尝试编写一个函数,以使用通用词干从现有变量在数据框中创建新变量。例如,我要创建:

df1$stem_new<- df1$stem_old1 + df1$stem_old2

反复,变量名称的stem部分将更改。

天真的我想要一个像这样的函数groupvars

groupvars <- function(stem){
df1$'stem'_new <- df1$'stem'_old1 + df1$'stem'_old2
} 

但是我不确定如何在R中最好地实现这一点。任何帮助或指向有用功能的指针将不胜感激。我尝试过弄乱paste0()names(),但到目前为止还没有运气。

1 个答案:

答案 0 :(得分:1)

这是一个小例子:

# example of original data
df = data.frame(stem_old1 = 1:3,
                stem_old2 = 11:13,
                z = 1:3)

df

#   stem_old1 stem_old2 z
# 1         1        11 1
# 2         2        12 2
# 3         3        13 3

# function (input dataframe and the column name pattern)
# 1. get the columns that match the pattern, calculate the row sums and save them as column v in your dataset
# 2. update column name from v to your pattern plus "_new"
# 3. return updated dataframe
f = function(d, x) {
  d$v = rowSums(d[,grepl(x, names(d))])
  names(d)[names(d) == "v"] = paste0(x,"_new")
  d }

# apply function
f(df, "stem")

#   stem_old1 stem_old2 z stem_new
# 1         1        11 1       12
# 2         2        12 2       14
# 3         3        13 3       16

注意,该函数最初将计算出的总和存储在名为v的(新)列中。因此,如果您的原始数据集已经有一个名为v的列,则会出现问题。