我正在将 R 中的一个函数转换为 Julia,但我不知道如何转换以下 R 代码:
I am converting a function in R to Julia, but I do not know how to convert the following R code:
x[x==0]=4基本上,x 包含数字行,但是只要有 0,我就需要将其更改为 4.数据集 x 来自二项分布.有人可以帮我在 Julia 中定义上述代码吗?
Basically, x contains rows of numbers, but whenever there is a 0, I need to change it to a 4. The data set x comes from a binomial distribution. Can someone help me define the above code in Julia?
推荐答案两个小问题两个长评论是:
Two small issues two long for a comment are:
在 Julia 0.7 中,您应该编写 x[x .== 0] .= 4(在赋值中也使用第二个点)
In Julia 0.7 you should write x[x .== 0] .= 4 (using a second dot in assignment also)
一般来说,它使用起来会更快,例如foreach 或循环而不是用 x .== 0 分配向量,例如:
In general it is faster to use e.g. foreach or a loop than to allocate a vector with x .== 0, e.g.:
julia> using BenchmarkTools julia> x = rand(1:4, 10^8); julia> function f1(x) x[x .== 4] .= 0 end f1 (generic function with 1 method) julia> function f2(x) foreach(i -> x[i] == 0 && (x[i] = 4), eachindex(x)) end f2 (generic function with 1 method) julia> @benchmark f1($x) BenchmarkTools.Trial: memory estimate: 11.93 MiB allocs estimate: 10 -------------- minimum time: 137.889 ms (0.00% GC) median time: 142.335 ms (0.00% GC) mean time: 143.145 ms (1.08% GC) maximum time: 160.591 ms (0.00% GC) -------------- samples: 35 evals/sample: 1 julia> @benchmark f2($x) BenchmarkTools.Trial: memory estimate: 0 bytes allocs estimate: 0 -------------- minimum time: 86.904 ms (0.00% GC) median time: 87.916 ms (0.00% GC) mean time: 88.504 ms (0.00% GC) maximum time: 91.289 ms (0.00% GC) -------------- samples: 57 evals/sample: 1更多推荐
在 Julia 中更改数据集中的值
发布评论