titeuf
titeuf

Reputation: 163

Use string output as a part of variable name for dataframe

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

Upvotes: 1

Views: 49

Answers (1)

s_baldur
s_baldur

Reputation: 33548

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

Upvotes: 3

Related Questions