Tori Tori - 2 months ago 5
R Question

R - write function and allow user input to name data frame column within function

I have written the following function:

create_dls <- function(injury_type, col1, col2){
injuries_10 = subset(dl2010, dl2010$Location %in% injury_type)
injuries_11 = subset(dl2011, dl2011$Location %in% injury_type)
on2010 = c()
on2011 = c()
for (mlbid in starting_pitchers$shared_players.MLBID){
if (mlbid %in% injuries_10$MLBID){
on2010 = c(on2010, 1)}
else {
on2010 = c(on2010, 0)}
if (mlbid %in% injuries_11$MLBID){
on2011 = c(on2011, 1)}
else {
on2011 = c(on2011, 0)}}
sp_predictor$col1 <<- on2010
sp_predictor$col2 <<- on2011
}


When I run the code as follows:

create_dls(shoulder_injuries, "2010_sDL", "2011_sDL")


I get the output:

> head(sp_predictor)
starting_pitchers.shared_players.MLBID col1 col2
1 112020 0 0
2 115399 0 0
3 115817 0 0
4 117955 0 0
5 119154 0 0
6 123801 0 0


What I want to do is have the column names of sp_predictor be user inputs in the function, instead of being named col1 and col2. Just for reference, I have tried the following, which did not work.

function(injury_type, col1="Column 1 Name", col2="Column 2 Name")

x=toString(col1)
sp_predictor$x <<- on2010

x=get("col1")
sp_predictor$x <<- on2010


None of the above has worked. (note: this is my first question posted on StackOverflow, if I've asked this question wrong please please let me know!)

Answer

Use [[ instead of $ when making your assignments to sp_predictor

create_dls <- function(injury_type, col1, col2){ 
    injuries_10 = subset(dl2010, dl2010$Location %in% injury_type)
    injuries_11 = subset(dl2011, dl2011$Location %in% injury_type)
    on2010 = c()
    on2011 = c()
    for (mlbid in starting_pitchers$shared_players.MLBID){
        if (mlbid %in% injuries_10$MLBID){
            on2010 = c(on2010, 1)}
        else {
            on2010 = c(on2010, 0)}
        if (mlbid %in% injuries_11$MLBID){
            on2011 = c(on2011, 1)}
        else {
            on2011 = c(on2011, 0)}}
   sp_predictor[[col1]] <<- on2010
   sp_predictor[[col2]] <<- on2011
}
Comments