R: How to pass two filepaths as parameters to a function? -


i'm trying pass 2 file paths parameters function. it's not accepting inputs. here's i'm doing:

partition<-function(d1,p2){       d1<-read.table(file = d1, fill = true)      p2<-read.table(file = p2, fill = true)   } 

and while calling function:

partition("samcopy.txt","partcopy.txt") 

the .txt not being read variables inside function. how make variables read table?

aidangawronski's approach works, programming standpoint should avoided! here more traditional answer problem.

partition<-function(d1,p2){      <- read.table(file = d1, fill = true)      b <- read.table(file = p2, fill = true)       res <- list(a,b)      names(res) <- c(d1,p2)      res } 

to understand why above approach "better", important understand environments , more r scoping rules. environments workspace. example, when first open r , begin assigning objects, these objects stored within global environment. example of environment when call function, function creates own environment comprised of parameters have passed function. doing r ensures when call function, has no "side effects" or said way not affect global environment.

let me show example. imagine begin r session, , assign d1 <- 1 in global environment. you're going want use d1 later on in analysis , shame if changed without knowing it, right?

if utilize aidangawronski's approach when call

partition<-function(d1,p2){  d1 <<- read.table(file = d1, fill = true) } 

the d1 in global environment change read.table(file = d1, fill = true). very dangerous! object assigned 1 thing thing , not warned of change.

the same problem, however, never occur approach have proposed. recommend in habit of using approach! if don't function can change things in global environment without knowing.

for more info read this, this or google "functions no side effects"

fyi there several other problems code. first need tell function return. did call function, assign stuff local environment , close function. functions return last line (as long not assignment). why in example, put res last line of function. not correctly assigning object. pass string d1 <- "text.txt", function , ask function following, "text.txt" <- read.table("text.txt",...). not make sense. need assign output read.table object. in example, assign them a , b.


Comments

Popular posts from this blog

javascript - Thinglink image not visible until browser resize -

firebird - Error "invalid transaction handle (expecting explicit transaction start)" executing script from Delphi -

mongodb - How to keep track of users making Stripe Payments -