2016-09-06 2 views
0

Ich habe die folgende Funktion geschrieben erlauben:R - Funktion schreiben und Benutzereingabe Name Datenrahmen Spalte in Funktion

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 
} 

Wenn ich den Code ausführen wie folgt:

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

ich die Ausgang:

> 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 

Was ich will ist die Spaltennamen von sp_predictor sein Benutzereingaben in der Funktion zu tun haben, anstatt Col1 und Col2 genannt zu werden. Nur als Referenz habe ich Folgendes versucht, was nicht funktioniert hat.

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 

Keines der oben genannten hat funktioniert. (Anmerkung: Dies ist meine erste Frage auf Stackoverflow geschrieben, wenn ich diese Frage gestellt habe falsch bitte lass es mich wissen!)

Antwort

0

Verwenden [[ statt $ wenn Ihre Aufträge zu 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 
} 
machen
Verwandte Themen