Cristian Cristian - 1 year ago 73
R Question

Using data from csv file as vector of characters in R

I am new to R and am trying to use the SocialMediaMineR package to resolve shortened URLs that I have stored in a csv dataset. This is done with the command get_url, which requires a vector of characters as the URLs to be resolved.

Let us say I want to resolve three URLS. If I manually create a vector with those three characters and launch the command, it works:

library(SocialMediaMineR)
url<- c("http://buff.ly/1bH9XaL", "http://buff.ly/1I4REcx", "http://buff.ly/1kMqoFs")
get_url(url, return.df = T)
... originalURL
1 http://buff.ly/1bH9XaL
2 http://buff.ly/1I4REcx
3 http://buff.ly/1kMqoFs
resolvedURL
1 https://www.storiedmind.com/relationship/11-relationship-traps-of-depression/?utm_source=buffer&utm_campaign=Buffer&utm_content=buffer8151c&utm_medium=twitter
2 http://inkygirl.com/inkygirl-main/2015/8/15/am-going-to-try-hard-not-to-be-like-these-writers-while-im-o.html?utm_content=bufferc6643&utm_medium=social&utm_source=twitter.com&utm_campaign=buffer
3 http://the7gracesofmarketing.com/2014/07/10-business-systems-to-help-your-one-person-enterprise-grow/?utm_content=buffer83b26&utm_medium=social&utm_source=twitter.com&utm_campaign=buffer


However, I would like the list of URLs to be taken directly from my csv file. I tried the following code with a csv file that contains the exact same three URLs as before:

library(SocialMediaMineR)
url_list = read.csv("~/Desktop/url2.csv", header = F)
as.character(url_list)
get_url(url_list)


But, I keep getting the following error:

Error : length(url) == 1 is not TRUE


For clarity, here is the structure of the data as read from the csv file:

> url_list<-read.csv("~/Desktop/url2.csv", header = F)
> dput(url_list)
structure(list(V1 = structure(1:3, .Label = c("http://buff.ly/1bH9XaL",
"http://buff.ly/1I4REcx", "http://buff.ly/1kMqoFs"), class = "factor")), .Names = "V1", class = "data.frame", row.names = c(NA,
-3L))


Why is this happening and how can I fix it? Any help would be hugely appreciated!

Answer Source

First of all you haven't read the data using argument stringsAsFactors = FALSE, so you have a column of objects of class factor. You must therefore do

url_list$V1 <- as.character(url_list$V1)

After this the following seems to work.

get_url(url_list$V1)

Note: The proper way of reading in the data would have been, like I've said above,

url_list = read.csv("~/Desktop/url2.csv", header = F, stringsAsFactors = FALSE)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download