Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a data table column that has special characters or space?

Tags:

r

data.table

I have the following data.table:

              Date     Time User% Sys% Wait% Idle% Busy PhysicalCPUs 
1: 01-APR-2015 00:15:28   0.7  0.9   0.1  98.4   NA            64
2: 01-APR-2015 00:30:32   0.7  0.9   0.3  98.1   NA            64
3: 01-APR-2015 00:45:39   0.5  0.7   0.3  98.4   NA            64
4: 01-APR-2015 01:00:46   0.6  0.8   0.3  98.3   NA            64
5: 01-APR-2015 01:15:51   0.5  0.7   0.1  98.6   NA            64

And I'm trying to plot a graphic with the following code:

g1 <- ggplot(CPU_ALL, aes(x = interaction(CPU_AL$Date, CPU_ALL$Time)
        , y = CPU_ALL$User%)) +
        geom_line() + 
        geom_point() +
        expand_limits(y=0) +
        xlab('Date/Time') + ylab('CPU Utilization (%)') +
        ggtitle('CPU ALL')

Afer run I get the following message:

anobre@segall:nmon$ CPU_ALL.R CPU_ALL_nmon.csv  
Error: unexpected input in: "g1 <- ggplot(CPU_ALL, aes(x = interaction(Date, Time)
        , y = User%)) +" Execution halted

I think the problem is when I try to access the columns User%, Sys%, Wait%, and Idle%. When I do CPU_ALL[,Date] it works fine, but when I try CPU_ALL[,User%] I get the following error message:

anobre@segall:nmon$ CPU_ALL.R CPU_ALL_nmon.csv 
Error: unexpected input in "CPU_ALL[,User%]"
Execution halted

Does anyone know how to access column names with special characters or spaces inside a data.table?

like image 569
Anderson Nobre Avatar asked Dec 09 '25 08:12

Anderson Nobre


1 Answers

You can use backtick ` sign.

library(data.table)
CPU_ALL=data.table(`User%`=1:2)
CPU_ALL$`User%`
# [1] 1 2
CPU_ALL[,`User%`]
# [1] 1 2
CPU_ALL[,.(`User%`)]
#    User%
# 1:     1
# 2:     2
CPU_ALL[`User%` %in% 1:2]
#    User%
# 1:     1
# 2:     2
CPU_ALL[["User%"]]
# [1] 1 2

It will work for space also.

like image 132
jangorecki Avatar answered Dec 11 '25 22:12

jangorecki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!