30

I have this sample code to create a new data frame 'new_data' from the existing data frame 'my_data'.

new_data = NULL
n = 10 #this number correspond to the number of rows in my_data
conditions = c("Bas_A", "Bas_T", "Oper_A", "Oper_T") # the vector characters correspond to the target column names in my_data
for (cond in conditions){
    for (i in 1:n){
        new_data <- rbind(new_data, c(cond, my_data$cond[i]))
    }
}

The problem is that my_data$cond (where cond is a variable, and not the column name) is not accepted.

How can I call a column of a data frame by using, after the dollar sign, a variable value?

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
this.is.not.a.nick
  • 2,631
  • 3
  • 21
  • 26
  • 11
    `$` is not really meant to be used programatically. It is meant to be a convenience for interactive use. Try using `mydata[i,cond]` instead. However, looking at your code I think you might benefit from looking at the `reshape` function, or indeed the `reshape2` package... – James Sep 12 '12 at 13:45
  • Note that `my_data` is a `data.frame` and `new_data` is a `matrix`. – GSee Sep 12 '12 at 13:56

3 Answers3

42

To access a column, use:

my_data[ , cond]

or

my_data[[cond]]

The ith row can be accessed with:

my_data[i, ]

Combine both to obtain the desired value:

my_data[i, cond]

or

my_data[[cond]][i]
mnel
  • 113,303
  • 27
  • 265
  • 254
Sven Hohenstein
  • 80,497
  • 17
  • 145
  • 168
  • cant we use `c$column`, where `c` is a matrix? I was getting `Error in c$col1 : $ operator is invalid for atomic vectors`... – Mahesha999 Oct 20 '16 at 12:09
  • @Mahesha999 You can't use `$` with matrices. – Sven Hohenstein Oct 20 '16 at 18:34
  • Out of curiosity, if for example we wanted to leverage the partial matching supported by `$` offers, couldn't we use something like `'$'(data,something(cond))` with something being one or a mix of functions that I don't fully understand such `as.symbol`, `as.expression`, `quote` `enquote` `substitute`etc ? – moodymudskipper May 28 '18 at 08:10
  • I want to ADD 106 columns to a dataframe that are the length of the dataframe but are filled with 0's. How do I loop over this? for (i in vector) { df$i <- vector(,lengthdf) } ??? – Emil Krabbe May 04 '21 at 09:05
5

I guess you need get().

For example,
get(x,list), where list is the list and x is the variable(can be a string), which equals list$x.

But in get(x,list), x can be a variable while using $, x cannot be a variable.

rankthefirst
  • 1,370
  • 2
  • 14
  • 26
1

$ works on columns, not individual column objects. It's a form of vectorization. The code

corrections$BookDate = as.Date(corrections$BookDate, format = "%m/%d/%Y")

converts the contents of the BookDate column of the corrections table from strings to Date objects. It performs it in one operation, assignment.

Do the following and it will fix your problem:

new_data <- rbind(new_data, c(cond, my_data$cond))
Jossie Calderon
  • 1,393
  • 12
  • 21