2

I foresee this question will have to be heavily edited by a more experienced R user as I'm unsure of the right terminologies to use.

Here is a reproducible dataframe. Would it be possible to obtain the object from global environment and slice it like a normal dataframe?

df1 <- data.frame(fruit=c("apple", "Orange", "Pear"), location = c("Japan", "China", "Nigeria"), price = c(32,53,12))

df1
   fruit location price
1  apple    Japan    32
2 Orange    China    53
3   Pear  Nigeria    12

Obtaining list of objects in global environment

allobj <- ls()
allobj[1]
"df1"

I understand that by using the noquote function, it returns the name of the object, which in this case is df1 - the name of my dataframe.

How do I treat this output as a named dataframe, in a base R slice? For instance,

(noquote(allobj[1]))[,1] #subset out only the 'fruit' column.

The above returns the error:

Error in unclass(x)[...] : incorrect number of dimensions

Is there a workaround for this?

Javier
  • 730
  • 4
  • 17
  • do `df2 <- get(obj[1])` and then extract the first column `df2[, 1]`. Is this what you are looking for? – Ronak Shah Jan 16 '19 at 06:28
  • Hmm, would it be possible to not have the assignment? Cos I intend to pass the object name i.e. df1 through a function – Javier Jan 16 '19 at 06:30

2 Answers2

3

You can use get and then subset the first column

get(obj[1])[1]

#   fruit
#1  apple
#2 Orange
#3   Pear
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
1

I have tried the same with small edit, please find it below and let me know if it suits

df1 <- data.frame(fruit=c("apple", "Orange", "Pear"), location = c("Japan", "China", "Nigeria"), price = c(32,53,12))

objs = ls()

get(objs[1])[,1] # for values as a vector
[1] apple  Orange Pear  
Levels: apple Orange Pear

get(objs[1])[1] #for column subset
   fruit
1  apple
2 Orange
3   Pear