[R] Accessing variables in a data frame

Bill.Venables at csiro.au Bill.Venables at csiro.au
Sun Jun 26 23:40:21 CEST 2011


Just to start things off:

> var.name <- c("gdp","inf","unp")
> var.id <- c("w","i")
> 
> x <- paste(var.name, rep(var.id, each=length(var.name)), sep="_")
> x
[1] "gdp_w" "inf_w" "unp_w" "gdp_i" "inf_i" "unp_i"
> 

Now the three differences:

gdp_w - gdp_i
inf_w - inf_i
unp_w - unp_i

Can be got using

dwi <- dat[, x[1:3]] - dat[, x[4:6]]

and the other three differences

gdp - gdp_w
inf - inf_w
unp - unp_w

by

dw <- dat[, var.name] - dat[, x[1:3]]

The results, in both cases, should be data frames

Bill Venables.
 

-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf Of Serguei Kaniovski
Sent: Sunday, 26 June 2011 10:01 PM
To: r-help at r-project.org
Subject: [R] Accessing variables in a data frame


Hello

My data.frame (dat) contains many variables named var.names and others
named var.names_var.id

For example

var.name <- c("gdp","inf","unp")
var.id <- c("w","i")

x <- paste(var.name, rep(var.id, each=length(var.name)), sep="_")

How can I access variables in the dama.frame by names listed in x, for
example to compute

gdp_w - gdp_i
inf_w - inf_i
unp_w - unp_i

or

gdp - gdp_w
inf - inf_w
unp - unp_w

without needing to code each difference separately?

Thanks for your help!
Serguei Kaniovski
	[[alternative HTML version deleted]]

______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list