0

I can subset a column named A from a data frame x_data using x_data$A. But if I do

some_string<-'A'
x_data$some_string

I get NULL. Can someone please explain why is it so. Thanks.

Aargo
  • 53
  • 1
  • 8
  • On the second line, R will only look for the symbol `some_string` within `x_data`. It doesn't matter whether you have a variable `some_string` defined in the global environment or not, as R won't look there. – Marius Feb 05 '18 at 05:57
  • Thanks for the explanation, – Aargo Feb 05 '18 at 06:04

1 Answers1

2

You can reference a data frame with the $ operator using a string literal, only a column. If you want to subset using a string, use the list syntax:

sub_df <- x_data[[some_string]]
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360