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).

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

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


2 Answers 2


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.

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))

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.

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 agree to our terms of service and acknowledge you have read our privacy policy.

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