Reputation: 21
I am a new student learning R and I have what should be an easy question but I am in brain lock.
I am using RStudio and I am trying to write a simple function to go to a url and bring back the csv (census table). I can do the individual lines to pull in the data...but I know I am missing something easy but I can't get there. If I run this
urlToRead <-"https://www2.census.gov/programs-surveys/popest/tables /2010-2011/state/totals/nst-est2011-01.csv"
and these
testFrame <- read.csv(url(urlToRead))
str(testFrame)
I can see a return 'testFrame' in my data and 'urltoread' in my Environment. Works just fine. My task is to try and write a basic function to do this. If I run my function below I get 'str' back in my Console, but no Data or Values
chris<- function(url)
{
urlToRead <-(url)
testFrame<- read.csv(url(urlToRead))
return(str(testFrame))
}
chris ("https://www2.census.gov/programs-surveys/popest/tables/2010-2011/state/totals/nst-est2011-01.csv")
I am sure that it is something simple, and I hope I formatted the question correctly, and I apologize for the long post, but I could use a kickstart
thank you
Chris
Upvotes: 2
Views: 346
Reputation: 1139
Change return(str(testFrame))
to return(testFrame)
or remove it completely.
Functions in R will basically only output what is in the 'return' command or, if no 'return' is present, it'll automatically output the last object generated. Your original code is forcing it to return the structure (str) of the data frame only, not the data frame itself.
EDIT: Just to clarify, if you remove the return
completely, you'll need to assign a new variable when you make the function call. e.g.csvData <- chris(url)
.
Upvotes: 3
Reputation: 322
chris<- function(url)
{
urlToRead <-(url)
testFrame<- read.csv(url(urlToRead))
return(testFrame)
}
testframe=chris ("https://www2.census.gov/programs-surveys/popest/tables/2010-
2011/state/totals/nst-est2011-01.csv")
Upvotes: 1