如何使在函数内创建的对象可在外部使用 [英] How to make object created within function usable outside

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

问题描述

我创建了一个生成矩阵的函数,但我不知道如何使该函数的输出在函数环境之外可用,以便例如将其保存在 csv 文件中.

I created a function which produces a matrix as a result, but I can't figure out how to make the output of this function usable outside of the function environment, so that I could for instance save it in csv file.

我的函数代码如下:

getTitle <- function(url) {
  webpage <- readLines(url)
  first.row <- webpage[1]
  start <- regexpr("<title>", first.row)
  end <- regexpr("</title>", first.row)
  title <- substr(first.row,start+7,end-1)
  return(title)
}

创建的函数采用 url 向量并返回 n*2 矩阵,其中包含 url 和页面标题:

getTitles <- function(pages) {
  my.matrix <- matrix(NA, ncol=2, nrow=nrow(pages))
  for (i in seq_along(1:nrow(pages))) {
    my.matrix[i,1] <- as.character(pages[i,])
    my.matrix[i,2] <- getTitle(as.character(pages[i,])) }
  return(my.matrix)
  print(my.matrix)}

在从此处 http://goo.gl/D9lLZ 的示例文件上运行此函数后,我使用 read.csv 函数导入该文件并命名为mypages"我得到以下输出:

After running this functions on a sample file from here http://goo.gl/D9lLZ which I import with read.csv function and name "mypages" I get the following output:

getTitles(mypages)
     [,1]                                               [,2]                                                
[1,] "http://support.google.com/adwords/answer/1704395" "Create your first ad campaign - AdWords Help"      
[2,] "http://support.google.com/adwords/answer/1704424" "How costs are calculated in AdWords - AdWords Help"
[3,] "http://support.google.com/adwords/answer/2375470" "Organizing your account for success - AdWords Help"

这正是我所需要的,但我希望能够将此输出导出到 csv 文件或重复使用以进行进一步操作.但是,当我尝试打印(my.matrix)时,我收到一条错误消息错误:找不到对象'my.matrix'"

This is exactly what I need, but I'd love to be able to export this output to csv file or reuse for further manipulations. However, when I try to print(my.matrix), I am getting an error saying "Error: object 'my.matrix' not found"

我觉得这是我知识上的基本差距,但有一段时间没有使用 R 并且无法解决这个问题.

I feel like it's quite basic gap in my knowledge, but have not been working with R for a while and could not solve that.

谢谢!谢尔盖

推荐答案

这很简单:使用 <<- 分配给全局.

That's easy: use <<- for assignment to a global.

但话又说回来,全局分配是邪恶的,而且不起作用.也许你宁愿回来包含您的函数的多个结果的列表?查看您的代码,似乎您的第二个函数可能会混淆 returnprint.确保返回正确的数据结构.

But then again, global assignment is evil and not functional. Maybe you'd rather return a list with several results from your function? Looking at your code, it seems that your second function may confuse the return and print. Make sure you return the correct data structure.

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

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