with
is handy and improves readability in an interactive context but can hurt your brain in a programming context where you are passing things back and forth to functions and dealing with things in different environments. In general within R, using symbols rather than names is a sort of "semantic sugar" that is convenient and readable in interactive use but mildly deprecated for programming [e.g. $
, subset
]). If you're willing to compromise as far as using a name ("a"
) rather than a symbol (a
) then I would suggest falling back to the simpler obj[[col]]
rather than using with
here ...
So, as a self-contained answer:
foo <- function(object,col) {
print(names(object))
print(object[[col]])
}
If you wanted to allow for multiple columns (i.e. a character vector)
foo <- function(object,col) {
print(names(object))
print(object[col])
}
edit: refraining from using subset
with a function, at @hadley's suggestion
(this will print the answer as a data frame, even if a single column is selected, which may not be what you want).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…