【问题标题】:R function with single argument to rename/combine variables with a similar stem具有单个参数的 R 函数用于重命名/组合具有相似词干的变量
【发布时间】:2019-03-15 06:18:01
【问题描述】:

作为一名偶尔的 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(),但到目前为止没有运气。

【问题讨论】:

  • 使用 df1[[paste0(stem,'_new')]] 等等...

标签: r function dataframe arguments parameter-passing


【解决方案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 的列,则会出现问题。

【讨论】:

  • 谢谢安东尼奥,非常感谢
猜你喜欢
  • 1970-01-01
  • 2014-11-13
  • 1970-01-01
  • 2020-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-24
相关资源
最近更新 更多