我写了以下函数:
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
}
当我按如下方式运行代码时:
create_dls(shoulder_injuries, "2010_sDL", "2011_sDL")
我得到了输出:
> 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
我想要做的是让sp_predictor的列名是函数中的用户输入,而不是命名为col1和col2。仅供参考,我尝试了以下,但没有用。
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
以上都没有奏效。 (注意:这是我在StackOverflow上发布的第一个问题,如果我已经问过这个问题,请告诉我!)
答案 0 :(得分:0)
在对[[
进行作业时,使用$
代替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
}