r - 如何访问包含特殊字符或空格的数据表列?

标签 r 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

我正在尝试使用以下代码绘制图形:

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')

运行后我收到以下消息:

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

我认为问题出在我尝试访问列 User%Sys%Wait%Idle %。当我执行 CPU_ALL[,Date] 时,它工作正常,但是当我尝试 CPU_ALL[,User%] 时,我收到以下错误消息:

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

有谁知道如何访问 data.table 中带有特殊字符或空格的列名?

最佳答案

您可以使用反引号 ` 符号。

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

它也适用于空间。

关于r - 如何访问包含特殊字符或空格的数据表列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32446986/

相关文章:

r - 在 R - 从 data.frame 中的所有行生成成对 data.frame

r - 使用 data.table 的 'by' 中的符号列表

r - 使用 "any"函数跨多个列的逻辑函数

r - findInterval() 在 data.table R 中具有不同的间隔

从长到宽 reshape 面板数据

r - R 中的函数 lapply(x, '[[' , VarNames[[type]]) 中的 '[[' 是什么意思?

r - 使用与列同名的变量对 data.table 进行子集化

r - 如何在函数内将 R data.table 列名与 cube(..., j = ,...) 一起使用?

function - 将变量名传递给 r 中的函数

r - 有条件地将字符串连接到多行