Dollar sign before a variable
Asked Answered
L

3

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?

Laxative answered 12/9, 2012 at 13:29 Comment(2)
$ 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...Seacock
Note that my_data is a data.frame and new_data is a matrix.Rosellaroselle
F
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]
Fraxinella answered 12/9, 2012 at 13:45 Comment(4)
cant we use c$column, where c is a matrix? I was getting Error in c$col1 : $ operator is invalid for atomic vectors...Rictus
@Rictus You can't use $ with matrices.Fraxinella
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 substituteetc ?Semiconductor
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) } ???Tillery
K
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.

Khan answered 12/9, 2012 at 13:29 Comment(0)
S
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))
Sanderson answered 10/7, 2016 at 19:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.