[R] substitute column data frame based on name stored in variable in r

Ivan Krylov kry|ov@r00t @end|ng |rom gm@||@com
Mon Aug 9 13:31:34 CEST 2021


On Mon, 9 Aug 2021 13:16:02 +0200
Luigi Marongiu <marongiu.luigi using gmail.com> wrote:

> df = data.frame(VAR = ..., VAL = ...)
> vect = letters[1:5]

What is the relation between vect and the column names of the data
frame? Is it your intention to choose rows or columns using `vect`?

> df[df[['vect[2]']] == 2, 'vect[2]']

'...' creates a string literal. If you want to evaluate an R
expression, don't wrap it in quotes.

I had assumed you wanted to put column names in the vector `vect`, but
now I'm just confused: `vect` is the same as df$VAR, not colnames(df).
What do you want to achieve?

Again, you can access the second column with much less typing by
addressing it directly: df[[2]]

Does it help if you consult [**] or some other tutorial on subsetting
in R?

-- 
Best regards,
Ivan

[**] 
https://cran.r-project.org/doc/manuals/r-release/R-intro.html#Index-vectors
https://cran.r-project.org/doc/manuals/r-release/R-intro.html#Lists



More information about the R-help mailing list