Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Call data from a specific column in a data frame using a object

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

> 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)?

>Solution :

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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading