0

I'm struggling to achieve something supposedly simple. I have dataframe df with columns a and b. If I call df$a, df$"a" df$`a`, it works. So I'm thiking I can assign a variable a string, and then use that. But if I do and try to get the column with it, I get Unknown or uninitialised column.

df = data.frame(a=(1:3), b=c("a", "b", "c"))
df$a # works
df$`a` # works
df$"a" # works

x <- "a"
df$x # error

How to solve this?

Marcel Braasch
  • 1,083
  • 1
  • 10
  • 19
  • 5
    use `df[,x]` instead – Adam Quek Jun 07 '22 at 12:57
  • 2
    as @AdamQuek indicates; or `df[[x]]` – langtang Jun 07 '22 at 13:01
  • Just to clarify the above two comments, `df[,x] or df[x]` returns a **single column data frame** whereas `df[[x]] or df$a` returns a **vector** – Sotos Jun 07 '22 at 13:12
  • @Sotos - You may have forgotten that `df[, x]` will return a vector, `df[, x, drop = FALSE]` is needed to return a single column data frame. – Ritchie Sacramento Jun 07 '22 at 13:23
  • @RitchieSacramento That's correct and interesting. I had it `as_tibble()` and that returns a data frame without the `drop` argument. Data frames on the other hand return a vector. – Sotos Jun 07 '22 at 13:42

0 Answers0