Reputation: 4951
I am trying to use lapply
so that I can apply a custom function on all elements of a vector in R. I am trying to avoid using for
loop here .
This is what I have so far:
writeToHDFS <- function(fileName){
print(fileName)
hdfs.init()
modelfile <- hdfs.file(fileName, "w")
hdfs.write(gaDataUser, modelfile)
hdfs.close(modelfile)
}
fileNames <- c("gaDataUser", "gaDataSession", "gaDataSources","gaDataEventTracking", "gaDataEcommerce", "gaDataEcommerce2", "gaDataEcommerce3", "gaDataEcommerce4")
lapply(fileNames,writeToHDFS(x))
I have variables with the names mentioned in the character vector fileNames
.
What I need to know:
How to pass each string from the vector fileNames
to function writeToHDFS
since I would like this function to be executed for every element in the vector.
How to use string name to access variables of that name in the function. For example:
At this line,I have to access variable with name same as string passed to fileName
variable in the function.
hdfs.write(variableWithData, modelfile)
3. Can I pass the variable fileName
to
modelfile <- hdfs.file(fileName, "w")
instead of passing a string for file name ?
Upvotes: 0
Views: 3808
Reputation: 73395
I am trying to use lapply so that I can apply a custom function on all elements of a vector in R
In this situation, you should use tapply
:
tapply(fileNames, 1:length(fileNames), writeToHDFS)
lapply
, is short for "list-apply", but fileNames
is a vector not a list.
Since you are already pretty well-aimed at using lapply
, you can learn from ?lapply
.
Upvotes: 2
Reputation: 2574
writeToHDFS(x) gives you return value of function. But you want to pass function so:
lapply(fileNames,writeToHDFS)
Upvotes: 1