我正在寻找一个函数,它接受一个向量并不断删除第一个值,直到向量的总和小于20.返回剩余的值.
我已经尝试了for-loop和while循环,但无法找到解决方案.
vec <- c(3,5,3,4,3,9,1,8,2,5)
short <- function(vec){
for (i in 1:length(vec)){
while (!is.na((sum(vec)) < 20)){
vec <- vec[i+1:length(vec)]
#vec.remove(i)
}
}
Run Code Online (Sandbox Code Playgroud)
预期输出应为:
1,8,2,5
小于20.
I have a vector of TRUEs and FALSEs:
x <- c(F,F,F,T,T,T,F,F,F,T,T,T,F,T,T)
Run Code Online (Sandbox Code Playgroud)
I'd like to elegantly (and in base) identify the position of the last TRUE before it changes to FALSE.
The following works, though, it seems like it could be simplified:
c((x[-1] != x[-length(x)]),T) & x
> FALSE FALSE FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE TRUE FALSE FALSE TRUE
Run Code Online (Sandbox Code Playgroud)
我维护一个依赖于重复调用的包deparse(control = c("keepNA", "keepInteger"))。control总是一样的,表达方式各不相同。deparse()似乎花了很多时间反复解释相同的选项集.deparseOpts()。
microbenchmark::microbenchmark(
a = deparse(identity, control = c("keepNA", "keepInteger")),
b = .deparseOpts(c("keepNA", "keepInteger"))
)
# Unit: microseconds
# expr min lq mean median uq max neval
# a 7.2 7.4 8.020 7.5 7.6 55.1 100
# b 3.0 3.2 3.387 3.4 3.5 6.0 100
Run Code Online (Sandbox Code Playgroud)
在某些系统上,冗余.deparseOpts()调用实际上占据了deparse()(此处为火焰图)的大部分运行时间。
我真的很想只调用.deparseOpts()一次,然后将数字代码提供给deparse(),但如果不.Internal()直接调用或调用 C 代码,这似乎是不可能的,从包开发的角度来看,这两种代码都不是最佳的。
deparse
# function (expr, width.cutoff = 60L, …Run Code Online (Sandbox Code Playgroud) 是否可以在指定行之后隐藏工作表中的所有行?
library("openxlsx")
# Create a workbook.
wb <- createWorkbook()
# Add a worksheet.
addWorksheet(wb, sheetName = "test", gridLines = FALSE)
# "Hide" all rows after row 37.
setRowHeights(wb, 1, 38:1048576, 0)
# Write workbook.
saveWorkbook(wb, "test.xlsx", overwrite = TRUE)
# inspect file size.
file.info("test.xlsx")
# size isdir mode mtime ctime atime exe
# test.xlsx 2621280 FALSE 666 2018-09-13 14:54:10 2018-09-13 14:54:07 2018-09-13 14:54:07 no
Run Code Online (Sandbox Code Playgroud)
似乎非常低效并且似乎使输出变得非常大(并且在尝试在 Excel 中打开它时速度很慢)。我认为它没有隐藏它,实际上只是将行高更改为 0?
我有以下data.frame(实际上它是数百万条记录).
我希望能够在电话号码与任何其他记录和任何电话号码位置匹配时分配组ID.
id <- c(1:5)
phone_1 <- c("444","", "333", "222", "")
phone_2 <- c("", "444", "111", "", "")
phone_3 <- c("222","", "", "", "111")
df <- data.frame(id, phone_1, phone_2, phone_3)
Run Code Online (Sandbox Code Playgroud)
理想的输出如下:
print(df)
# id phone_1 phone_2 phone_3 ID
# 1 1 444 222 1
# 2 2 444 1
# 3 3 333 111 2
# 4 4 222 1
# 5 5 111 2
Run Code Online (Sandbox Code Playgroud)
理想情况下,我想使用一种data.table方法,因为速度很重要.
请注意,缺失值(""或NA)应视为不可比较(或上述所有内容都在同一组中).
r ×5
vector ×2
cumsum ×1
data.table ×1
for-loop ×1
logic ×1
loops ×1
openxlsx ×1
while-loop ×1