将在函数中创建的列添加到r中的数据框架中



我已经搜索并尝试了多个以前问过的问题,可能与我的问题相似,但没有一个工作。

我在R中有一个名为df2的数据帧,一个名为df2$col的列。我创建了一个函数来接受df、df$col和两个参数,这两个参数是我想在函数中创建和处理的两个新列的名称。在函数完成运行之后,我想要一个包含两个新列的返回df。我确实得到了这两列,但它们是以函数shell中的占位符命名的。见下文:

df2 = data.frame(col = c(1, 3, 4, 5), 
col1 = c(9, 6, 8, 3),
col2 = c(8, 2, 8, 4))

我创建的函数将接受col并对其执行一些操作;返回转换后的颜色,以及两个新创建的列:

no_way <- function(df, df_col_name, df_col_flagH, df_col_flagL) {
lo_perc <- 2
hi_perc <- 6
df$df_col_flagH <- as.factor(ifelse(df_col_name<lo_perc, 1, 0))
df$df_col_flagL <- as.factor(ifelse(df_col_name>hi_perc, 1, 0))
df_col_name <- df_col_name + 1.4
df_col_name <- df_col_name * .12

return(df)
}

当我调用函数no_way(df2, col, df$new_col, df$new_col2)时,不是使用col, col1, col2, new_col1, new_col2获得df,而是获得前三个正确的参数名称,但获得最后两个的参数名称。比如df col1 col2 df_col_flagH df_col_flagL。我本质上想要函数返回df和我在调用它时给它的新列的名称。请帮助。

我不知道你的函数想做什么,但这可能会给你指明正确的方向:

no_way <- function(df = df2, df_col_name = "col", df_col_flagH = "col1", df_col_flagL = "col2") {

lo_perc <- 2
hi_perc <- 6

df[[df_col_flagH]] <- as.factor(ifelse(df[[df_col_name]] < lo_perc, 1, 0)) # as.factor? 
df[[df_col_flagL]] <- as.factor(ifelse(df[[df_col_name]] > hi_perc, 1, 0))

df[[df_col_name]] <- (df[[df_col_name]] + 1.4) * 0.12 # Do in one step      

return(df)     
}

我需要用新的列名作为字符串来调用函数:

no_way(mball, 'TEAM_BATTING_H', 'hi_TBH', 'lo_TBH')

此外,我必须在函数的目标列周围使用括号。

最新更新