[R] r: functions
TEMPL Matthias
Matthias.Templ at statistik.gv.at
Thu Feb 24 10:51:22 CET 2005
Hello,
I have no errors with simple1:
d <- matrix(c(1,2,3,1,6,10,10,6,7),ncol=3)
colnames(d) <- c("one", "two", "three")
x<- d[,c(1,2)]
y<-d[,3]
> y
[1] 10 6 7
> simple1(x,y)
[[1]]
Call:
lm(formula = ydata ~ xdata)
Coefficients:
(Intercept) xdataone xdatatwo
-6 21 -5
With:
y <-d[,3, drop=FALSE]
> y
[,1]
[1,] 10
[2,] 6
[3,] 7
> simple1(x,y)
[[1]]
Call:
lm(formula = ydata ~ xdata)
Coefficients:
(Intercept) xdataone xdatatwo
-6 21 -5
You have an error with function simple, which you have not shown! (you have only shown function simple1, simple2 and simple3)
Look at simple3 now:
simple3<-function(xdata,ydata)
{
datas<-data.frame(xdata=xdata,ydata=ydata)
ofit<-lm(ydata~xdata, data=datas)
list(ofit)
}
> simple3(x,y)
[[1]]
Call:
lm(formula = ydata ~ xdata, data = datas)
Coefficients:
(Intercept) xdataone xdatatwo
-6 21 -5
Best,
Matthias
> -----Ursprüngliche Nachricht-----
> Von: r-help-bounces at stat.math.ethz.ch
> [mailto:r-help-bounces at stat.math.ethz.ch] Im Auftrag von Clark Allan
> Gesendet: Donnerstag, 24. Februar 2005 10:17
> An: r-help at stat.math.ethz.ch
> Betreff: [R] r: functions
>
>
> hi all
>
>
> i have a function that uses two inputs, say xdata and ydata.
> An example is the following,
>
> simple1<-function(xdata,ydata)
> {
> ofit<-lm(ydata~xdata)
> list(ofit)
> }
>
> say i use arbitray number for xdata and ydata such that
>
> D =
> x1 x2 y
> 1 1 10
> 2 6 6
> 3 10 7
>
>
> x<-D[,1:2]
>
> and
>
> y<-D[,3]
>
> if one uses these inputs and rund the program we get the following:
>
> >simple(xdata=x,ydata=y)
> Error in model.frame(formula, rownames, variables, varnames,
> extras, extranames, :
> invalid variable type
>
> why does this happen!
>
> i can get results if i change the program as follows:
>
> simple2<-function(xdata,ydata)
> {
> ofit<-lm(as.matrix(ydata)~as.matrix(xdata))
> list(ofit)
> }
>
> but then the variable names, if they exist, are not
> preserved. how can i preserve these names.
>
> the results are now:
>
> > simple2(xdata=x,ydata=y)
> [[1]]
>
> Call:
> lm(formula = as.matrix(ydata) ~ as.matrix(xdata))
>
> Coefficients:
> (Intercept) as.matrix(xdata)x1 as.matrix(xdata)x2
> -6 21 -5
>
> i've tried converting xdata and ydata to data frames but i
> still get errors.
>
> simple3<-function(xdata,ydata)
> {
> xdata<-as.data.frame(xdata)
> ydata<-as.data.frame(ydata)
> ofit<-lm(ydata~xdata)
> list(ofit)
> }
>
> i.e.
>
> > simple3(xdata=x,ydata=y)
> Error in model.frame(formula, rownames, variables, varnames,
> extras, extranames, :
> invalid variable type
>
> please help!
>
> thanking you in advance
>
> ***
> allan
>
More information about the R-help
mailing list