Learn R Programming

vkR is an R package which provides access to the VKontakte (VK) API.

Installation

To get the current released version from CRAN:

install.packages("vkR")

To get the current development version from github:

install.packages("devtools")
devtools::install_github("Dementiy/vkR")
library("vkR")

Authorization

Most API requests require the use of an access token. VK has several types of authorization mechanisms. Check out the documentation for more details.

vkOAuth(CLIENT_ID, 'SCOPE', 'EMAIL', 'PASSWORD')

where:

  • CLIENT_ID - is an application ID. You have to create new Standalone-app in VK to get ID (or use the already existing).
  • SCOPE - the list of comma separated access rights, e.g. 'friends,groups'- provide the access to user friends and groups. List of all rights can be found here.
  • EMAIL and PASSWORD - username and password.

If the EMAIL and PASSWORD have been omitted, a browser window will be opened. In the address bar an access token will be shown. Access token must be copied and passed as an argument into the following function:

setAccessToken(access_token = 'YOUR ACCESS TOKEN')

Example of use

At your own risk you can use mongodb and mongolite package for storing data:

> db_init()
> wall <- getWallExecute(domain="data_mining_in_action", count=0, use_db=TRUE, progress_bar=TRUE)
|======================...======================| 100%
> show_collections()
    db            collection       suffix count
1 temp data_mining_in_action         wall   232

If connection was aborted by some reasons we don't lose our data:

> wall <- getWallExecute(domain='privivkanet', count=0, use_db = T, progress_bar = T)
|=================                              |  25%
Show Traceback
 
 Rerun with Debug
 Error in curl::curl_fetch_memory(url, handle = handle) : 
  Operation was aborted by an application callback ...
> show_collections()
    db            collection       suffix count
1 temp data_mining_in_action         wall   232
2 temp           privivkanet         wall   916
> wall <- getWallExecute(domain='privivkanet', count=0, offset=916, use_db = T, progress_bar = T)
|======================...======================| 100%
> show_collections()
    db            collection       suffix count
1 temp data_mining_in_action         wall   232
2 temp           privivkanet         wall  3664

You can specify the collection name:

> wall <- getWallExecute(domain="data_mining_in_action", count=0, 
        use_db=TRUE, db_params=list('collection'='dm', 'suffix'='posts'), progress_bar=TRUE)
|======================...======================| 100%
> show_collections()
    db            collection       suffix count
1 temp data_mining_in_action         wall   232
2 temp           privivkanet         wall  3664
3 temp                    dm        posts   232

> friends <- getFriends()
> users <- getUsersExecute(friends$items, use_db = TRUE, db_params=list('collection'='my_friends'), progress_bar = TRUE)
> show_collections()
    db            collection       suffix count
1 temp data_mining_in_action         wall   232
2 temp           privivkanet         wall  3664
3 temp                    dm        posts   232
4 temp            my_friends                141

For load collection into a namespace you can use db_load_collection function:

> db_load_collection('data_mining_in_action', 'wall')
 Imported 232 records. Simplifying into dataframe...
> ls()
[1] "temp.data_mining_in_action.wall"
> nrow(temp.data_mining_in_action.wall)
[1] 232

Building a Friend Graph:

my_friends <- getFriends(fields = 'sex')
my_friends <- filter(my_friends$items, is.na(deactivated))
network <- getNetwork(my_friends$id)

library("igraph")
g <- graph.adjacency(as.matrix(network), weighted = T, mode = "undirected")
layout <- layout.fruchterman.reingold(g)
plot(g, layout = layout)

Analyzing community activity:

domain <- 'nipponkoku'
wall <- getWallExecute(domain = domain, count = 0, progress_bar = TRUE)
metrics <- jsonlite::flatten(wall$posts[c("date", "likes", "comments", "reposts")])
metrics$date <- as.POSIXct(metrics$date, origin="1970-01-01", tz='Europe/Moscow')

library(dplyr)
df <- metrics %>% 
  mutate(period = as.Date(cut(date, breaks='month'))) %>% 
  group_by(period) %>%
  summarise(likes = sum(likes.count), comments = sum(comments.count), reposts = sum(reposts.count), n = n())

library(ggplot2)
library(tidyr)
ggplot(data=gather(df, 'type', 'count', 2:5), aes(period, count)) + geom_line(aes(colour=type)) +
  labs(x='Date', y='Count')

You can find more examples in examples directory.

Copy Link

Version

Install

install.packages('vkR')

Monthly Downloads

192

Version

0.2

License

GPL-3

Issues

Pull Requests

Stars

Forks

Maintainer

Dmitriy Sorokin

Last Published

September 29th, 2020

Functions in vkR (0.2)

boardGetComments

Returns a list of comments on a topic on a community's discussion board
databaseGetFaculties

Returns a list of faculties (i.e., university departments)
collection_exists

Check if collection exists
create_empty_collection

Create empty collection
databaseGetSchools

Returns a list of schools
db_insert

Insert object into existing collection
getFriends

Returns a list of user IDs or detailed information about a user's friends
databaseGetStreetsById

Returns information about streets by their IDs
db_load

Load all collections from db for specified data base
getFriendsBy25

Returns a list of friends IDs for the specified users
age_predict

Predict age for the specified user
db_get_connection

Get a mongo connection object
execute

A universal method for calling a sequence of other methods while saving and filtering interim results
db_get_collection

Get collection
filterAttachments

Filtering attachments by type
db_getName

The current database name
areFriends

Checks the friendship status between two users
databaseGetCitiesById

Returns information about cities by their IDs
getPaths

Returns a list of paths between two users
getStatus

Returns data required to show the status of a users and/or communities
db_save

Save object to db
getGroupsById

Returns information about communities by their IDs
groupsSearch

Returns a list of communities matching the search criteria
likesGetList

Returns a list of IDs of users who added the specified object to their Likes list
getGroupsForUsers

Returns a list of the communities for the specified users
db_update

Update existing records
db_init

Initialize database
likesGetListForObjects

Returns a list of IDs of users who added the specified objects to their Likes list
handle_captcha

Captcha error handler
me

Returns current user ID
db_getActive

The current database name
databaseGetSchoolClasses

Returns a list of available classes
databaseGetChairs

Returns list of chairs on a specified faculty
db_drop_collection

Drop collection
databaseGetRegions

Returns a list of regions
databaseGetCities

Returns a list of cities
getAccessToken

Get access token
databaseGetCountries

Returns a list of countries
getCountryByCityId

Get country ID and title by given city ID
getArbitraryNetwork

Building a friend graph for an arbitrary list of users
getMutualExecute

Returns a list of user IDs of the mutual friends of two users
handle_validation

Validation error handler
getWallExecute

Returns a list of posts on a user wall or community wall
get_stop_words

Get stop words list for russian language
getMutual

Returns a list of user IDs of the mutual friends of two users
has_error

Get error code from response
vkPost

Create post object
messagesGet

Returns a list of the current user's incoming or outgoing private messages
or

Logical or operator
postGetComments

Returns a list of comments on a post on a user wall or community wall
setRepeats

Set maximum number of repeats
try_handle_network_error

Try to handle network error
setTimeout

Set timeout
use_db

Switch database
getGroupsMembers

Returns a list of community members
messagesGetHistory

Returns message history for the specified user or group chat
getFriendsFor

Returns a list of friends IDs for the specified users
getUsersExecute

Returns detailed information on arbitrary number of users
getGroups

Returns a list of the communities to which a user belongs
getWall

Returns a list of posts on a user wall or community wall
getEgoNetwork

Building a friend graph
messagesGetHistoryAll

Returns all message history for the specified user or group chat
vkOAuth

Client authorization
vkOAuthWeb

Client authorization (for web application)
vkR

Access to VK API via R
wallGetReposts

Returns information about reposts of a post on user wall or community wall
wallSearch

Allows to search posts on user or community walls
boardGetCommentsList

Returns a list of comments on a community's discussion board
messagesSplitByDate

Split messages by days, weeks, months
clear_text

Clear text
newsfeedSearch

Returns search results by statuses
try_handle_error

Check response for errors
tag2Id

Returns user id by tag
databaseGetUniversities

Returns a list of higher education institutions
db_drop

Drop database
wallGetCommentsList

Returns a list of comments on a user wall or community wall
wallGetComments

Returns a list of comments on a post on a user wall or community wall
getGroupsMembersExecute

Returns a list of community members
getTopics

Returns a list of topics on a community's discussion board
db_load_collection

Load collection from db
getTopicsExecute

Returns a list of topics on a community's discussion board
db_metaConnection

Get meta connection
profile_fields

Helper function for working with profile fields
request_delay

Delaying a request if necessary
repeat_last_query

Repeat last function call
show_dbs

Show databases
show_collections

Show collections
getURLs

Extract URLs from messages
usersGetFollowers

Returns a list of IDs of followers of the user in question, sorted by date added, most recent first
getUsers

Returns detailed information on users
queryBuilder

Returns a query string
usersGetSubscriptions

Returns a list of IDs of users and communities followed by the user
messagesSend

Sends a message.
messagesGetHistoryExecute

Returns message history for the specified user or group chat
usersSearch

Returns a list of users matching the search criteria
vkApply

Apply a method over a vector of objects
search.getHints

Allows the programmer to do a quick search for any substring
saveAsGEXF

Converts the given igraph object to GEXF format and saves it at the given filepath location
setAPIVersion

Set API version
setAccessToken

Set access token
wallGetById

Returns a list of posts from user or community walls by their IDs
vk_stop

Custom error
boardGetCommentsExecute

Returns a list of comments on a topic on a community's discussion board
databaseGetCountriesById

Returns information about countries by their IDs