Krishna Chaurasia
Krishna Chaurasia

Reputation: 9572

Filtering the key value pair in hadoop reducer function in R

I want to know how can I put conditions to filter out key, value pair in hadoop reducer function. For example, in the word count example given below, how can I get on those words whose count is greater than some threshold value say, 3.

library(rmr2)
library(rhdfs)

# initiate rhdfs package
hdfs.init()

map <- function(k,lines) {
  words.list <- strsplit(lines, '\\s')
  words <- unlist(words.list)
  return( keyval(words, 1) )
}

reduce <- function(word, counts) {
  keyval(word, sum(counts))
}

wordcount <- function (input, output=NULL) {
  mapreduce(input=input, output=output, input.format="text", map=map, reduce=reduce)
}

## read text files from folder example/wordcount/data
hdfs.root <- 'example/wordcount'
hdfs.data <- file.path(hdfs.root, 'data')

## save result in folder example/wordcount/out
hdfs.out <- file.path(hdfs.root, 'out')

## Submit job
out <- wordcount(hdfs.data, hdfs.out) 

## Fetch results from HDFS
results <- from.dfs(out)
results.df <- as.data.frame(results, stringsAsFactors=F)
colnames(results.df) <- c('word', 'count')

head(results.df)

Upvotes: 0

Views: 696

Answers (1)

piccolbo
piccolbo

Reputation: 1315

reduce <- function(word, counts) {
  if(sum(counts) > 3)
    keyval(word, sum(counts))
}

Upvotes: 1

Related Questions