有没有办法防止data.table在通过引用分配新列后打印新的data.table?我收集的标准行为是
library(data.table)
example(data.table)
DT
# x y v
# 1: a 1 42
# 2: a 3 42
# 3: a 6 42
# 4: b 1 11
# 5: b 3 11
# 6: b 6 11
# 7: c 1 7
# 8: c 3 8
# 9: c 6 9
DT[,z:=1:nrow(DT)]
# x y v z
# 1: a 1 42 1
# 2: a 3 42 2
# 3: a 6 42 3
# …Run Code Online (Sandbox Code Playgroud) 这在精神上与这个问题有关,但必须在机制上有所不同.
如果您尝试缓存knitr包含data.table :=分配的块,那么它就好像该块尚未运行,后来的块看不到该影响:=.
知道为什么会这样吗?knitr检测对象如何更新,以及如何data.table混淆它?
看起来你可以通过这样做来解决这个问题DT = DT[, LHS:=RHS].
示例:
```{r}
library(data.table)
```
Data.Table Markdown
========================================================
Suppose we make a `data.table` in **R Markdown**
```{r, cache=TRUE}
DT = data.table(a = rnorm(10))
```
Then add a column using `:=`
```{r, cache=TRUE}
DT[, c:=5]
```
Then we display that in a non-cached block
```{r, cache=FALSE}
DT
```
The first time you run this, the above will show a …Run Code Online (Sandbox Code Playgroud) 我知道on.exitR 中的功能,这很棒.它在调用函数退出时运行表达式,正常或作为错误的结果.
我想要的是表达式仅在调用函数正常返回时运行,而不是在出错的情况下运行.我有多个函数可以正常返回的点,以及可能失败的多个点.有没有办法做到这一点?
myfunction = function() {
...
on.exit( if (just exited normally without error) <something> )
...
if (...) then return( point 1 )
...
if (...) then return( point 2 )
...
if (...) then return( point 3 )
...
return ( point 4 )
}
Run Code Online (Sandbox Code Playgroud) 首先,让我们生成如下数据:
library(data.table)
data <- data.table(date = as.Date("2015-05-01")+0:299)
set.seed(123)
data[,":="(
a = round(30*cumprod(1+rnorm(300,0.001,0.05)),2),
b = rbinom(300,5000,0.8)
)]
Run Code Online (Sandbox Code Playgroud)
然后我想使用自定义函数多次操作多列而无需手动输入。 add <- function(x,n) (x+n)
我提供如下的for循环代码:
add <- function(x,n) (x+n)
n <- 3
freture_old <- c("a","b")
for(i in 1:n ){
data[,(paste0(freture_old,"_",i)) := add(.SD,i),.SDcols =freture_old ]
}
Run Code Online (Sandbox Code Playgroud)
您能告诉我一个lapply版本而不是for循环吗?