【发布时间】:2014-07-15 18:48:12
【问题描述】:
我搜索了 SO 并找到了 similar question,但我仍然无法使用它。
我对 R 编程比较陌生,所以我很感激这个帮助。
假设我有一个data.frame:
df <- data.frame(State = c("NJ", "MA", "CA", "CA", "MA"),
Sales = c(15, 100, 30, 56, 60),
Price = c(34, 52, 21, NA, 20),
stringsAsFactors = FALSE)
现在我想要一个函数来创建一个新的data.frame,它只有一个给定的状态......所以我写道:
state_function <- function(state) {
#Subset the rows in the state from all rows
new_df <- df[df[,"State"] == state, ]
## I will do many other things inside the function ##
summary(new_df)
return(new_df)
}
state_function ("NJ")
但是现在我想在这个函数之外重新使用这个 data.frame, new_df ..(我想概括这个例子).. 我该怎么做?一般来说,我想使用我在函数中创建的对象或data.frame,而不是函数。
【问题讨论】:
-
只分配?
new_df <- state_function ("NJ")