我已经定义了一种使用类 test 打印向量的方法:
print.test <- function(x, ...) {
x <- formatC(
as.numeric(x),
format = "f",
big.mark = ".",
decimal.mark = ",",
digits = 1
)
x[x == "NA"] <- "-"
x[x == "NaN"] <- "-"
print.default(x)
}
Run Code Online (Sandbox Code Playgroud)
这适用于以下情况
a <- c(1000.11, 2000.22, 3000.33)
class(a) <- c("test", class(a))
print(a)
[1] "1.000,11" "2.000,22" "3.000,33"
Run Code Online (Sandbox Code Playgroud)
这也有效:
round(a)
[1] "1.000,0" "2.000,0" "3.000,0"
Run Code Online (Sandbox Code Playgroud)
这不会:
median(a)
[1] 2000.22
class(median(a))
[1] "numeric"
Run Code Online (Sandbox Code Playgroud)
现在我的问题是:我是否需要为这个类编写一个自定义方法来使用中值,例如,如果是这样,它会是什么样子或者有另一种方式(因为我只是希望这个类以某种格式打印数据) ?
我正在尝试子集给定的data.table
DT <- data.table(
a = c(1:20),
b = (3:4),
c = (5:14),
d = c(1:4)
)
Run Code Online (Sandbox Code Playgroud)
在函数中由参数命名列表
param <- list(a = 1:10,
b = 2:3,
c = c(5, 7, 10))
Run Code Online (Sandbox Code Playgroud)
我可能在这里有些卡住,但是我当然不想实现像这样的丑陋的东西。特别是因为它不是很动态。
DT[(if (!is.null(param$a))
a %in% param$a
else
TRUE)
&
(if (!is.null(param$b))
b %in% param$b
else
TRUE)
&
(if (!is.null(param$c))
c %in% param$c
else
TRUE)
&
(if (!is.null(param$d))
d %in% param$d
else
TRUE)]
Run Code Online (Sandbox Code Playgroud)
a b c d
1: 1 3 5 1
2: 3 3 7 3
Run Code Online (Sandbox Code Playgroud)
有什么想法如何使用命名列表的名称在data.table或base R中以优雅的方式实现这一点,以使用关联值对data.table中的对应列进行子集化?谢谢!
编辑 …