0

I want to access a column in a dataframe, and the column name is stored in a string variable.

I have found this question answered for other languages, and for accesing a variable, but not for a column within a dataframe.

For example:

> df <- iris[1:3,]

  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa

> x <- "Sepal.Length"

I want to access the first column of the dataframe df by using x.

I have naively tried the following, without success:

df$[[x]]
df$[x]
df$get(x)

I imagine it should be straightforward, but I haven't been able to find it. Thanks

1 Answers1

1

From me:

df[x]

From @Rui Barradas:

Or df[[x]]. [MillionC's] returns a sub-data.frame, this one is a vector.

From @coffeinjunky:

The first two approaches work if you drop the $, as @MillionC has pointed out. For subsetting both columns and rows, you can use df[row_ind, col_ind]. Your get approach works with with, as in with(df, get(x)), though I can't think of an example when this construct is needed to subset a dataframe.