Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Paste function to construct existing data frame name and evaluate in R

Tags:

dataframe

r

I am working with a long list of data frames.

Here is a simple hypothetical example of a data frame:

DFrame<-data.frame(c(1,0),c("Yes","No"))

colnames(DFrame)<-c("ColOne","ColTwo")

I am trying to retrieve a specified column of the data frame using paste function.

get(paste("DFrame","$","ColTwo",sep=""))

The get function returns the following error, when trying to retrieve a specified column:

Error in get(paste("DFrame", "$", "ColTwo", sep = "")) :object 'DFrame$ColTwo' not found

When I enter the constructed name of the data frame DFrame$ColTwo it returns the desired output of the second column.

If I reconstruct an example without the '$' sign then I get the desired answer from the get function. For example the code yields 2:

enter code here Ans <- 2

get(paste("An","s",sep=""))

[1] 2

I am looking for the same desired outcome, but struggling to get past the error that the object could not be found.

I also attempted using the following format, but the quotation in the column name breaks the paste function:

paste("DFrame","[,"ColTwo"]",sep="")

Thank you very much for the input, Kind regards

like image 473
sempedocles Avatar asked Oct 20 '25 03:10

sempedocles


1 Answers

You can do that using the following syntax:

get("DFrame")[,"ColTwo"]

You can use paste() in both of these strings, for example:

get(paste("D", "Frame", sep=""))[,paste("Col", "Two", sep="")]

Edit: Despite someone downvoting this answer without leaving a comment, this does exactly what the original poster asked for. If you feel that it does not or is in some way dangerous, I would encourage you to leave a comment.

like image 114
Rob Hall Avatar answered Oct 21 '25 17:10

Rob Hall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!