如何使在函数内创建的对象在外部可用 [英] How to make object created within function usable outside
问题描述
我创建了一个生成矩阵的函数,但我不知道如何使该函数的输出在函数环境之外可用,以便我可以将其保存在 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 向量并返回带有 url 和页面标题的 n*2 矩阵:
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.
但话又说回来,全局赋值是邪恶的,没有功能.也许你宁愿回来一个包含多个函数结果的列表?查看您的代码,似乎您的第二个函数可能会混淆 return
和 print
.确保返回正确的数据结构.
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屋!