0

I've got an R script that works fine on its own to scrape tweets using the twitteR package. But when I try to automate this script on my mac using the crontab command, I get this error message:

/Users/Simon/WLU/projects_folder/ON18/get_tweets.R: line 1: syntax error near 
unexpected token `twitteR'
/Users/Simon/WLU/projects_folder/ON18/get_tweets.R: line 1: `library(twitteR)'

Do I need to add a #/usr/bash command or something like that to initialize the R script?

library(twitteR)
options(httr_oauth_cache=T)
consumer_key<-'yYol52znZBdtxnwQFpekMyCek'
consumer_secret<-'UMo8h70zYtrd5HSnjCGw1hnG88kfPmvu1wWxL1VvPWVYwpguu6'
access_token<-'1102181509-5hBh8OE7Ehz5NhWVBqpk1olp1dOmWiIK5B9ypzy'
access_token_secret<-'XbYZYWuMGHT5wCDzvDsDHMX3wI5KDzBJ9NQsh1Jj6I'
setup_twitter_oauth(consumer_key, consumer_secret, access_token, 
access_token_secret)

#Get #onpoli tweet
onpoli<-searchTwitter('#onpoli', resultType='recent', n=200)
#Get pcoldr
pcpoldr<-searchTwitter('#pcpoldr', resultType='recent', n=200)
#Get PCPO tweets
pcpo<-searchTwitter('#pcpo', resultType='recent', n=200)
#Turn to data.frames
onpolidf<-twListToDF(onpoli)
pcpoldrdf<-twListToDF(pcpoldr)
pcpodf<-twListToDF(pcpo)
#Write out to .csv files 
write.csv(onpolidf, './Tweets/onpoli.csv', append=T)
write.csv(pcpoldrdf, './Tweets/pcpoldr.csv', append=T)
write.csv(pcpodf, './Tweets/pcpo.csv', append=T)
quite(save='no')
miken32
  • 42,008
  • 16
  • 111
  • 154
spindoctor
  • 1,719
  • 1
  • 18
  • 42

2 Answers2

1

You need to provide cron with something executable to run. Even if the script is marked executable, in the absence of a shebang, it will not know how to execute this file. Instead, the shell will try and run it as a shell script. This results in a syntax error.

Easiest is to call Rscript, passing it the script name:

5 0 * * * Rscript /Users/Simon/WLU/projects_folder/ON18/get_tweets.R

Or you can make the script itself executable:

chmod +x /Users/Simon/WLU/projects_folder/ON18/get_tweets.R

Add a shebang:

#!/usr/bin/env Rscript

And call the script directly:

5 0 * * * /Users/Simon/WLU/projects_folder/ON18/get_tweets.R
miken32
  • 42,008
  • 16
  • 111
  • 154
0

Thanks for this. Actually it turned out that it couldn't find rscript. So I had to modify it to read /usr/local/bin/Rscript /Users/Simon/WLU/projects_folder/ON18/get_tweets.R

I've seen this solution elsewhere. Apparently if I get around to re-installing R it will work.

Should I mark this solved somehow?

spindoctor
  • 1,719
  • 1
  • 18
  • 42
  • You should **upvote** _all answers_ that were helpful, and **mark accepted** the _one answer_ that best answered your question. This will mark the question as "closed," and give you some reputation on the site. See https://stackoverflow.com/help/someone-answers for more information. – miken32 Feb 18 '18 at 17:56
  • (This includes your own answers by the way. If you figured out the answer yourself, give yourself the check mark!) – miken32 Feb 19 '18 at 15:46