我是R的新手。我知道如何用Java编写map reduce。我想在R中尝试同样的方法。所以任何人都可以帮助提供任何samle代码吗?R中的MapReduce有固定格式吗?
请发送除此之外的任何链接:https://github.com/RevolutionAnalytics/RHadoop/wiki/Tutorial
任何示例代码都会更有帮助。
当您想用Java以外的语言实现map reduce(使用Hadoop)时,您可以使用一种称为流的功能。然后,数据通过STDIN(readLines())被馈送到映射器,通过STDOUT(cat())返回Hadoop,然后通过STDIN再次被馈送到reducer(readLines()),最后通过STDOUT(cat(())脱口而出。
以下代码取自我写的一篇文章,该文章是关于用R for Hadoop编写map reduce作业的。代码应该是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/