0

Probably a fairly simple question, but couldn't find anything specific for it. Lets say I have the following data frame

A
     Hello World
   1   5     6
   2   5     6

If you want to fetch the the values from the Hello column you would usually just do it with

A$Hello

But is there a way to fetch the column values with a predefined variable like this?

col <- "Hello"
A$col

The latter returns NULL for me

MikeKatz45
  • 545
  • 5
  • 16

2 Answers2

1

Try A[col]:

## Hello
##   <dbl>
## 1     5
## 2     5

Essentially, just uses another form of indexing. This works because col is a string.

ladylala
  • 223
  • 1
  • 6
  • this was useful, but not using double bracket syntax actually yields a table rather than a numerical vector like A$Hello does. – MikeKatz45 Apr 07 '19 at 04:24
  • that's true - sorry I didn't completely think through what you might want (i.e. data frame versus vector) – ladylala Apr 07 '19 at 04:47
1
# A tibble: 2 x 2
  hello world
  <dbl> <dbl>
1     5     6
2     5     7
> col = 'hello'
> A[[col]]
[1] 5 5
liuminzhao
  • 2,385
  • 17
  • 28