Since I am new to R, I have pulled this code together in kind of a rag-tag way, but I am wondering, is there something similar to list comprehensions (in Python) I can use in R to make this simpler? Or a better way of doing this? I am trying to fetch the total amount of reputation a user has accumulated on Stack Exchange. I am ideally looking for a way to remove the for loop and use the sum function on a subset of items (from the API response).

library(httr)
s = 0
for(i in content(GET(paste("http://api.stackexchange.com/users/",readline(),"/associated",sep="")))$items) {
  q=i$reputation
  if (q>101) 
    s=s+q
}
print(s)

Sample input would be a user's id, like 10400443.

up vote 2 down vote accepted

R does not offer list comprehensions like Python, but a similar thing called the apply family of functions. In addition, there is packages called purrr that offers similar functionality with a more user-friendly interface. Below is an example how to compute the sum using these tools.

library('httr')
user_url <- paste0("http://api.stackexchange.com/users/", readline(), "/associated")
dat <- content(GET(user_url))$items

sum(vapply(dat, function(x) ifelse(x$reputation > 101, x$reputation, 0), 1))

library('purrr')
sum(map_dbl(dat, ~ifelse(.x$reputation > 101, .x$reputation, 0)))

It's simple to extract all reputation and subsequently sum an index. This is instead of performing the ifelse inside the *apply function to demonstrate indexing.

library(httr)
allc <- content(GET(paste0("http://api.stackexchange.com/users/",'10400443',"/associated")))
allci <- allc$items

# get all reputation out of list
allrep <- sapply(allci,`[[`,'reputation')

# sum only index of > 101
sum(allrep[allrep > 101])

I'm not familiar with Python, but it appears that indexing in R serves the same purpose as list comprehension in Python - list comprehension in r

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.