1

I am coming from STATA and would like to something as followed:

dataframe = data.frame(
  a = c("test1", "test2", "test3"), 
  b = c(1,2,3)
)

varnames = colnames(dataframe)

head(dataframe$b) # second last line
head(dataframe$varnames[2]) # last line

 

My goal is that the two last lines give me the same output. Basically I would like to somehow use the value stored in varnames[2] (namely "b") and use it as an input for the last code line (as it is used in the second last line). This is quite easy with STATA but I don't know how to do it in R. Could someone help?

Thx

titeuf
  • 133
  • 1
  • 10
  • This might help - https://stackoverflow.com/questions/18222286/dynamically-select-data-frame-columns-using-and-a-character-value – Ronak Shah Aug 07 '20 at 14:41

1 Answers1

3

You can extract a vector from data.frame with $ but also with [[.

head(dataframe[[varnames[2]]]) 

Note that if you are using the index anyway you can do it directly:

head(dataframe[[2]]) 

Some more example to ponder, using the inbuilt iris dataset:

smalliris <- head(iris)

smalliris["Sepal.Length"] # data.frame
subset(smalliris, select = Sepal.Length) # data.frame
all.equal(smalliris["Sepal.Length"], subset(smalliris, select = Sepal.Length)) # TRUE
smalliris[["Sepal.Length"]] # vector
smalliris$Sepal.Length # vector
all.equal(smalliris$Sepal.Length, smalliris[["Sepal.Length"]]) # TRUE
s_baldur
  • 29,441
  • 4
  • 36
  • 69