重用在R中的函数中创建的对象 [英] Reuse an object created in a function in R

查看:40
本文介绍了重用在R中的函数中创建的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜索了SO,并找到了

I have searched SO and found a similar question, but I still can't get it to work.

我对R编程很陌生,因此感谢您的帮助.

I am rather new to R programming, so I appreciate this help.

假设我有一个 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 ...所以我写道:

Now I want a function that creates a new data.frame that just has a given state... So I wrote:

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 .

But now I want to re-use this data.frame, new_df , outside of this function ..(and I want to generalize this example) .. How can I do this? In general, I want to use a object or data.frame that I create in a function, outside of a function.

推荐答案

在运行函数时将值分配给变量:

Assign the value to a variable when running the function:

new_df <- state_function("NJ")

这篇关于重用在R中的函数中创建的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆