0

I am trying to get a column x in one data frame named df using R language and I tried four methods below:

df = data.frame(x = 1, y = 1:10)
# 1st method
df$x

# 2nd method
df$"x"

#3rd method
s = "x"
df$s

#4th method
s = as.name(x)
df$s

I expect the four methods to return the same result

[1] 1 1 1 1 1 1 1 1 1 1

However, only the 1st and 2nd method work. Why it happens and if I have to get the column value using a variable, how to modify the 3rd and 4th method?

  • I think this will help you: [Understanding Non-Standard Evaluation. Part 1: The Basics](https://thomasadventure.blog/posts/understanding-nse-part1/). Basically, R looks for a column named `s` in `df` in the 3rd and 4th examples. – neilfws Feb 02 '21 at 04:57

1 Answers1

2

We can use [[ instead of $

df[[s]]
akrun
  • 874,273
  • 37
  • 540
  • 662