user3022875
user3022875

Reputation: 9018

Cannot access column of data frame

I have some data in a results 3-column data frame when I print results I see:

 results

TIMESTAMP                 SYMBOL_NAME         "t.price"
1 2014-10-17 14:00:00       GOOG                   400.25

Notice the "" around the t.price column

When I go to access the t.price column like it comes back null.

 results$t.Price
 NULL

when I do

  names(results)   

I see

[1] "TIMESTAMP"        "SYMBOL_NAME"        "\"t.PRICE\"" 

Can you tell me what is going on and why the "" is appearing or how I can access t.price?

Upvotes: 5

Views: 1968

Answers (3)

Rich Scriven
Rich Scriven

Reputation: 99331

You can remove the extra quotes with gsub

results
#             TIMESTAMP SYMBOL_NAME "t.price"
# 1 2014-10-17 14:00:00        GOOG    400.25
results$t.price
# NULL
names(results)[3] <- gsub('\"', "", names(results)[3])
results$t.price
# [1] 400.25

Just to be safe, you might want to run it on all the names of the data set (just remove both [3]).

Upvotes: 3

Hans
Hans

Reputation: 2910

Whatever the source of your data frame is, it appears that the t.Price column is surrounded by quotation marks. These in turn are escaped by \ as \" as otherwise "" would be the end of a string of 0 length.

Methods to work around this are suggested by the comments, you can access this by the index of the column or by renaming the columns, which can be done by assigning to names.

names(results) <- c("name1", "name2", "name3")

Upvotes: 3

IRTFM
IRTFM

Reputation: 263301

Try this:

names(results) <- make.names( names(results) )

That's the same function that gets applied when read.table and its descendants are used.

Upvotes: 3

Related Questions