Mark
Mark

Reputation: 45

With vs. lapply - why does with not work here?

I am trying to learn R and can't really figure out when to use with appropriately. I was thinking about this example:

The goal is to convert "dstr" and "died" in the whole dataframe "stroke" (in the ISwR database) to date format in several ways (just for practice). I've managed to do it like this:

#applying a function to the whole data frame - use the fact that data frames are lists actually
rawstroke=read.csv2(system.file("rawdata","stroke.csv",package="ISwR"),na.strings=".")
names(rawstroke)=tolower(names(rawstroke))
ix=c("dstr","died")
rawstroke[ix]=lapply(rawstroke[ix],as.Date,format="%d.%m.%Y")
head(rawstroke)

However, when I try using with function it does not give data frame as output, but only writes the definition of the function myfun. Here is the code I tried.

myfun=function(x)
{y=as.Date(x,format="%d.%m.%Y")
 return(y)}
rawstroke=read.csv2(system.file("rawdata","stroke.csv",package="ISwR"),na.strings=".")
names(rawstroke)=tolower(names(rawstroke))
ix=c("dstr","died")
bla=with(rawstroke[ix],myfun)
head(bla)

If somebody could help me with this, it would be great.

Upvotes: 1

Views: 61

Answers (1)

Aaron - mostly inactive
Aaron - mostly inactive

Reputation: 37814

Yeah, this doesn't seem like a job for with. To use your function here, you'd just replace as.Date in your first code with myfun and remove the format parameter, like

rawstroke[ix]=lapply(rawstroke[ix], myfun)

with is used to more cleanly access variables in data frames and environments. For example, instead of

t.test(dat$x, dat$y)

you could do

with(dat, t.test(x, y))

Upvotes: 2

Related Questions