在 Julia 中更改数据集中的值

Ell*_*lie 6 r julia

我正在将 R 中的函数转换为 Julia,但我不知道如何转换以下 R 代码:

x[x==0]=4
Run Code Online (Sandbox Code Playgroud)

基本上,x 包含数字行,但每当有 0 时,我需要将其更改为 4。数据集 x 来自二项式分布。有人可以帮我在 Julia 中定义上面的代码吗?

Bog*_*ski 3

两个需要评论的小问题是:

在 Julia 0.7 中你应该这样写x[x .== 0] .= 4(在赋值中也使用第二个点)

foreach一般来说,使用 eg或循环比使用 分配向量更快x .== 0,例如:

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
Run Code Online (Sandbox Code Playgroud)