在Julia中更改数据集中的值 [英] Change values in a data set in Julia
问题描述
我正在将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中更改数据集中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!