你最喜欢的单人班车是R什么?
请包含一个简短的伴随示例,并限制每个帖子一个提示.注意,;是作弊.
示例:计算x[i] / x[i-1]向量x,
x <- 1:10
Reduce("/", as.data.frame(embed(x, 2)))
Run Code Online (Sandbox Code Playgroud)
(从R-help收集,我忘了谁/何时)
编辑:在一些最初的争议之后,看起来问题现在重新开放参赛作品.
Ric*_*ton 14
如果要记录在其名称中创建文件的时间(可能是为了使其唯一,或防止覆盖),请尝试使用此单行函数.
timestamp <- function(format = "%y%m%d%H%M%S")
{
strftime(Sys.time(), format)
}
Run Code Online (Sandbox Code Playgroud)
用法是,例如,
write.csv(
some_data_frame,
paste("some data ", timestamp(), ".csv", sep = "")
)
Run Code Online (Sandbox Code Playgroud)
得到奇数或偶数指数.
odds <- function(x) seq_along(x) %% 2 > 0
evens <- function(x) seq_along(x) %% 2 == 0
Run Code Online (Sandbox Code Playgroud)
用法是,例如,
odds(1:5)
evens(1:5)
Run Code Online (Sandbox Code Playgroud)
我经常需要假数据来说明回归问题.代替
X <- replicate(2, rnorm(100))
y <- X[,1] + X[,2] + rnorm(100)
df <- data.frame(y=y, X=X)
Run Code Online (Sandbox Code Playgroud)
我们可以用
df <- transform(X <- as.data.frame(replicate(2, rnorm(100))),
y = V1+V2+rnorm(100))
Run Code Online (Sandbox Code Playgroud)
产生与结果相关的两个不相关的预测因子y.
从矢量或数据框中删除NaN(每隔一段时间就会令人讨厌)(在R-help上找到一些)
is.na(x) <- is.na(x)
Run Code Online (Sandbox Code Playgroud)
例:
> x <- c(1, NaN, 2, NaN, 3, NA)
> is.na(x) <- is.na(x)
> x
[1] 1 NA 2 NA 3 NA
Run Code Online (Sandbox Code Playgroud)
将Excel日期转换为R日期.答案改编自Paul Murrell的代码.
excel_date_to_r_date <- function(excel_date, format)
{
#excel_date is the number of days since the 0th January 1900. See
#http://www.stat.auckland.ac.nz/~paul/ItDT/HTML/node67.html
strftime(as.Date(as.numeric(excel_date) - 2, origin = "1900-01-01"), format)
}
Run Code Online (Sandbox Code Playgroud)
用法是,例如,
excel_date_to_r_date(40700, "%d-%m-%Y")
Run Code Online (Sandbox Code Playgroud)