3
votes

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

2
it is not entirely clear to me why you would reference a column by a paste functionmtoto

2 Answers

1
votes

Stop trying to use paste and get entirely.

The whole point of having a list (of data frames, say) is that you can reference them using names:

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

#A list of data frames
l <- list(DFrame,DFrame)

#The data frames in the list can have names
names(l) <- c("DF1",'DF2')

# Now you just use `[[`
> l[["DF1"]][["ColOne"]]
[1] 1 0
> l[["DF1"]][["ColTwo"]]
[1] Yes No 
Levels: No Yes

If you have to, you can use paste to construct the indices passed inside [[.

1
votes

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.