如何在R中写入map reduce?

时间:2012-07-26 05:49:11

标签: r mapreduce

我是R.的新手。我知道如何在Java中编写map reduce。我想在R中尝试相同的。所以任何人都可以帮助提供任何samle代码,并且R中的MapReduce有任何固定的格式。

请发送除此之外的任何链接:https://github.com/RevolutionAnalytics/RHadoop/wiki/Tutorial

任何示例代码都会更有帮助。

1 个答案:

答案 0 :(得分:2)

如果要使用Java以外的语言实现map(使用Hadoop),则可以使用名为streaming的功能。然后通过STDIN(readLines())将数据传送到映射器,通过STDOUT(cat())返回到Hadoop,然后通过STDIN(readLines())再次传递给reducer,最后通过STDOUT(cat())进行脱节。

以下代码取自我在编写地图减少作业的article中使用R for Hadoop。代码应该算2克,但我会说简单到看MapReduce明智的是什么。

# map.R

library(stringdist, quietly=TRUE)

input <- file("stdin", "r")

while(length(line <- readLines(input, n=1, warn=FALSE)) > 0) {
   # in case of empty lines
   # more sophisticated defensive code makes sense here
   if(nchar(line) == 0) break

   fields <- unlist(strsplit(line, "\t"))

   # extract 2-grams
   d <- qgrams(tolower(fields[4]), q=2)

   for(i in 1:ncol(d)) {
     # language / 2-gram / count
     cat(fields[2], "\t", colnames(d)[i], "\t", d[1,i], "\n")
   }
}

close(input)

-

# reduce.R

input <- file("stdin", "r")

# initialize variables that keep
# track of the state

is_first_line <- TRUE

while(length(line <- readLines(input, n=1, warn=FALSE)) > 0) {
   line <- unlist(strsplit(line, "\t"))
   # current line belongs to previous
   # line's key pair
   if(!is_first_line &&
      prev_lang == line[1] &&
      prev_2gram == line[2]) {
        sum <- sum + as.integer(line[3])
   }
   # current line belongs either to a
   # new key pair or is first line
   else {
     # new key pair - so output the last
     # key pair's result
     if(!is_first_line) {
       # language / 2-gram / count
       cat(prev_lang,"\t",prev_2gram,"\t",sum,"\n")
     }
     # initialize state trackers
     prev_lang <- line[1]
     prev_2gram <- line[2]
     sum <- as.integer(line[3])
     is_first_line <- FALSE
   }
}

# the final record
cat(prev_lang,"\t",prev_2gram, "\t", sum, "\n")

close(input)

http://www.joyofdata.de/blog/mapreduce-r-hadoop-amazon-emr/