Home > OS >  Call data from a specific column in a data frame using a object
Call data from a specific column in a data frame using a object

Time:03-30

I am trying to call data to a new data frame based on objects specifying a column in a data frame.

Here is a reproducible example, showing that I cannot achieve the aimed result:

dataframe1 <- data.frame('first' = seq(1:5),
                         'second' = letters[seq(1:5)])

specifcdata1 <- 'dataframe1[first]'                         
specifcdata2 <- 'dataframe1$second'

dataframe2 <- data.frame('Specific 1' = tail(specifcdata1, 1),
                         'Specific 2' = tail(specifcdata2, 1))

Resulting in:

> dataframe2
        Specific.1       Specific.2
1 dataframe1[first] dataframe1$second

The aimed result is:

> dataframe2
  Specific.1 Specific.2
1          5          e

Considering dataframe1,

> dataframe1
  first second
1     1      a
2     2      b
3     3      c
4     4      d
5     5      e

QUESTION: How can we call the object (data, not the stored characters)?

CodePudding user response:

You are looking for the combination of parse() and eval(). I also added quotation marks in 'dataframe1["first"]' or else in would not have worked.

dataframe1 <- data.frame('first' = seq(1:5),
                         'second' = letters[seq(1:5)])

specifcdata1 <- 'dataframe1["first"]'                         
specifcdata2 <- 'dataframe1$second'

dataframe2 <- data.frame('Specific 1' = tail(eval(parse(text = specifcdata1)), 1),
                         'Specific 2' = tail(eval(parse(text = specifcdata2)), 1))

dataframe2
#>   first Specific.2
#> 5     5          e

Created on 2022-03-30 by the reprex package (v2.0.1)

  • Related