+1 vote
in Programming Languages by (71.8k points)

I have the following data frame. I want to access data from each column dynamically at run time. If I use the $ operator, I need to provide the column name. Is there any other way to get the column data without the $ operator?

> df

   x y  z  w

1 10 1 11 11

2 20 2 12 22

3 30 3 13 33

4 40 4 14 44

1 Answer

+1 vote
by (351k points)
selected by
 
Best answer

You can create a vector of columns and then use each element from that vector to access the data from each column. You do not need to use the $ operator.

Here is an example:

df <- data.frame(x=c(10,20,30,40), y=c(1,2,3,4),z=c(11,12,13,14), w=c(11,22,33,44))
cols <- colnames(df)
for (col in cols){
  print(df[[col]])
}

So, instead of using the $ operator, I am using python style [[]] to access the column at run time.

The above code returns the following output:

[1] 10 20 30 40
[1] 1 2 3 4
[1] 11 12 13 14
[1] 11 22 33 44

Related questions

+5 votes
1 answer
+3 votes
1 answer
+2 votes
1 answer
+5 votes
1 answer
+5 votes
1 answer
asked Jul 6, 2021 in Programming Languages by kush (40.5k points)

...