[R] Accessing columns in data.frame using formula
Uwe Ligges
ligges at statistik.uni-dortmund.de
Tue Feb 24 21:54:49 CET 2004
Paul Lemmens wrote:
>
> Hello!
>
> I'm trying the hard way to use a formula, in a function, to specify the
> names of several important columns in a data.frame. Maybe I'm just battling
> to figure out the right search terms :-( This is on XP, R 1.8.1.
>
> So, for instance,
>
> wery[1:5,]
>
> V1 V2 V3 V4 V5 congr V7 V8 V9 ok RT
> 1 1 1 960 520 1483 c 1 r r 1 760
> 2 1 2 1060 450 3753 c 1 r r 1 555
> 3 1 3 980 470 5758 c 2 l l 1 432
> 4 1 4 1060 440 7693 c 1 r r 1 424
> 5 1 5 1020 440 9578 i 1 l l 1 369
>
> I already figured out how to get to the parts of the formula,
>
> tst <- function(f=RT~congr+ok, data=wery) {
> thingy <- all.vars(f)
> resp <- thingy[1]
> facts <- thingy[-1]
I guess you are really looking for model.frame() and friends, but not
for the stuff written down below. I may be wrong ... so here we go:
> # and how to get data from the data.frame.
> eval(parse(text=resp), env=data)
Why not data[[resp]]
> # But now, I would like to do here what I'd do on the console as
> # wery$ok <- factor(wery$ok), so here data$facts[2] <- factor(data$facts[2])
> # This won't work here. How do I continu?
data[[facts[2]]] <- factor(data[[facts[2]]])
> # Or perhaps also
> # data.tmp <- data$resp[data$facts[1] == 'i']
data.tmp <- data[[resp]][data[[facts[1]]] == 'i']
Uwe Ligges
> }
>
> thank you,
> Paul Lemmens
>
> P.S:
> str(wery)
> `data.frame': 150 obs. of 11 variables:
> $ V1 : int 1 1 1 1 1 1 1 1 1 1 ...
> $ V2 : int 1 2 3 4 5 6 7 8 9 10 ...
> $ V3 : int 960 1060 980 1060 1020 1010 1060 1010 1090 1090 ...
> $ V4 : int 520 450 470 440 440 530 580 530 560 540 ...
> $ V5 : int 1483 3753 5758 7693 9578 11488 13423 15368 17548 19678 ...
> $ congr: Factor w/ 2 levels "c","i": 1 1 1 1 2 2 2 1 1 2 ...
> $ V7 : int 1 1 2 1 1 1 1 2 2 2 ...
> $ V8 : Factor w/ 2 levels "l","r": 2 2 1 2 1 1 1 1 1 2 ...
> $ V9 : Factor w/ 2 levels "l","r": 2 2 1 2 1 2 1 1 1 2 ...
> $ ok : int 1 1 1 1 1 0 1 1 1 1 ...
> $ RT : int 760 555 432 424 369 291 403 526 500 458 ...
>
> --
> Paul Lemmens
> NICI, University of Nijmegen ASCII Ribbon Campaign /"\
> Montessorilaan 3 (B.01.05) Against HTML Mail \ /
> NL-6525 HR Nijmegen X
> The Netherlands / \
> Phonenumber +31-24-3612648
> Fax +31-24-3616066
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
More information about the R-help
mailing list