比较如果满足条件(R),则复位序列的有效方法 [英] Comp. Efficent way of resetting sequence if condition met ( R )
本文介绍了比较如果满足条件(R),则复位序列的有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问题:
如果要满足条件,我想重设(1,2)
序列(主题更改)。
我有个
和 if
个循环可以做到这一点,但是毫不奇怪,该方法非常慢。
关于更有效方法的任何建议(例如,涉及应征家庭)?
I want to reset a (1,2)
sequence if condition is met (subject changes).
I have for
and if
loops that will do this but, unsurprisingly, that method is very slow.
Any suggestions (e.g., involving the apply family) for a more efficent method?
当前:
subj odd_even
a
a
a
b
b
b
b
c
c
c
目标:
Goal:
subj odd_even
a 1
a 2
a 1
b 1
b 2
b 1
b 2
c 1
c 2
c 1
df = data.frame( subj = c("a","a","a","b","b","b","b", "c","c","c"), odd_even = "" )
推荐答案
为此,我喜欢序列
函数:
df$odd_even <- 2L - sequence(table(df$subj)) %% 2L
data.table是另一种选择:
data.table is another option:
library(data.table)
setDT(df)
df[, odd_evenDT := 2L - seq_along(.I) %% 2L, by = subj]
基准:
set.seed(42)
df <- data.frame(subj = sort(sample(as.character(1:1e4), 1e5, TRUE)))
DT <- data.table(df)
library(microbenchmark)
microbenchmark(roland1 = 2L - sequence(table(df$subj)) %% 2L,
roland2 = DT[,2L - seq_along(.I) %% 2L, by = subj],
roland3 = 2L - sequence(rle(as.integer(df$subj))$lengths) %% 2L,
jeremy = df %>% group_by(subj) %>%
mutate(odd_even = 2 - (row_number() %% 2)),
frank = 2L - ave(as.integer(df$s),df$s,FUN=seq_along) %% 2L,
flick = ave(seq_along(df$subj), df$subj, FUN=function(x) rep(c(1,2), length.out=length(x))),
times = 10, unit = "relative")
# Unit: relative
# expr min lq mean median uq max neval
# roland1 5.820459 5.754497 5.0368686 5.404110 4.0853039 4.847161 10
# roland2 1.110919 1.057952 0.9840653 1.037428 0.7939004 1.176258 10
# roland3 1.000000 1.000000 1.0000000 1.000000 1.0000000 1.000000 10
# jeremy 5.024087 4.941366 4.3491117 4.635534 3.5144515 4.277011 10
# frank 2.036816 1.944603 1.7809168 1.831937 1.6459597 1.607283 10
# flick 3.655127 3.621457 3.2453089 3.473188 2.7717947 3.198285 10
这篇关于比较如果满足条件(R),则复位序列的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文