Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
313 views
in Technique[技术] by (71.8m points)

r - How to use with/within inside a function?

I'm struggling to understand why does this doesn't work.

df <- data.frame(a=1:10, b=1:10)

foo <- function(obj, col) {
   with(obj, ls())
   with(obj, print(col))
}
foo(df, a)

[1] "a" "b"

Error in print(col) : object 'a' not found

If this does work:

with(df, print(a))
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...