julia-lang , Analog in Julia to coefficients() in R

Analog in Julia to coefficients() in R


Tag: julia-lang

How can I extract coefficients from a GLM run in Julia. In R, I can fit a regression and just use coefficients():

lm.fit <- lm(y ~ . - 1, data = data.ols)

Is there a similar way to access coefficients in Julia so that I can use them in future formulas that I write?

My Julia code is:

olsFitFinal = fit(LinearModel, Y ~ -1 + Base + TRc + TCkRc + TcRc + R + RT,

It seems that an answer at http://bit.ly/1EwSeCg implies the use of coefs() but that does not work for me.


Doing some more searching I found the solution:



Speeding up `using Distributions` in Julia

On my machine, with the development version of Julia, the command import Distributions takes 6.6 seconds. Is there a way to make this faster? Is static precompilation going to be part of Julia 0.4? _ _ _ _(_)_ | A fresh approach to technical computing (_) | (_) (_) |...

Can I use a subtype of a function parameter in the function definition?

I would like to use a subtype of a function parameter in my function definition. Is this possible? For example, I would like to write something like: g{T1, T2<:T1}(x::T1, y::T2) = x + y So that g will be defined for any x::T1 and any y that is a subtype...

Julia: How do I create a macro that returns its argument?

My question is quite similar to this one, but with a difference. I want to create a macro (or whatever) that behaves this way: julia> @my-macro x + 2 :(x + 2) (note that x + 2 is not enclosed in quotes). Is there something like that in Julia? And...

Julia: Instantiated type parameters

How does one define a type that, like Array, has a concrete/instantiated type parameter? My initial instinct was that it would be like this: immutable Foo{N::Integer} data::Array{Float64, N} end However, this generates the following error: ERROR: syntax: malformed type parameter list The following code is acceptable: immutable Foo{N} data::Array{Float64, N}...

Composite types in Julia: Dictionaries as a named field?

I'd like to make a composite type that includes a dictionary as one of its named fields. But the obvious syntax doesn't work. I'm sure there's something fundamental that I don't understand. Here's an example: type myType x::Dict() end Julia says: type: myType: in type definition, expected Type{T<:Top}, got Dict{Any,Any}...

In Julia, can a macro access the inferred type of its arguments?

In Julia, is there a way to write a macro that branches based on the (compile-time) type of its arguments, at least for arguments whose types can be inferred at compile time? Like, in the example below, I made up a function named code_type that returns the compile-time type of...

How to parse output of external command in Julia?

Let us say that I have an external command called "Busca01.x" which returns three integers separated by tabs, like this: [email protected]: Busca01.x 192 891 9029 So, I can call this from julia and store the result as a string using either readall or readchomp. I need the data as an...

What mistake did I make in this matrix multiplication in Julia?

In Julia: In [1]: M1 = [1 3 4; 45 64 33; 456 3 454;] Out [1]: 3x3 Array{Int64,2}: 1 3 4 45 64 33 456 3 454 In [2]: M1 * inv(M1) Out [2]: 3x3 Array{Float64,2}: 1.0 6.93889e-18 -8.67362e-19 0.0 1.0 -2.08167e-17 -1.42109e-14 -8.88178e-16 1.0 M1 * inv(M1) is...

Extend many standard methods to a new custom vector type

I build a new vector type: type MyType x::Vector{Float64} end I want to extend lots of the standard methods, eg addition, subtraction, element-wise comparison, etc to my new type. Do I need to define a method definition for each of them, eg: +(a::MyType, b::MyType) = a.x + b.x -(a::MyType, b::MyType)...

Julia macros may treat variable and literals differently?

Hi fellow Julia users, Why does this using HDF5, JLD s = "It would take me 48 hours to recompute this." filename_no_ext = "eric_demo_file" @save filename_no_ext readdir() @load "eric_demo_file" evaluate differently from this? using HDF5, JLD s = "It would take me 48 hours to recompute this." filename_no_ext = "eric_demo_file"...

Julia equivalent of dplyr's bind_cols and bind_rows

Is there a Julia equivalent of dplyr's bind_cols and bind_rows? Specifically, I'm looking for a bind_rows function which will match column names regardless of order and fill in NA's for non-matching columns Edit: R Example of both: library(dplyr) df1 = data.frame(a = 1, b = 1) df2 = data.frame(b =...

Exact decimal arithmetic in Julia

Due to the nature of floating-point math, .4 * .4 = 0.16000000000000003 in Julia. I want to get the mathematically correct answer of 0.16, in a CPU-efficient way. I know round() works, but that requires prior knowledge of the number of decimal places the answer occupies, so it isn't a...

Subtypes of composite types

I'm trying to make a vectorized version of ismatch. Base.ismatch function ismatch(vector::Vector, regex::Regex) [ismatch(regex, string) for string in vector] end This works, but this Base.ismatch function ismatch(vector::Vector{String}, regex::Regex) [ismatch(regex, string) for string in vector] end doesn't because Vector{ASCIIString} <: Vector{String} is false. Is there any way to get around this?...

Sapply (from R) equivalent for Julia?

Suppose I have an 2 dimensional array and I want to apply several functions to each of its columns. Ideally I would like to get the results back in the form of a matrix (with one row per function, and one column per input column). The following code generates the...

Matching of array elements in Julia

With x = Any[[1,2],[2,3],[3,4],[4,5]], I tried the following line with Julia0.4.0 x[ x .== [3,4] ] but it resulted in an error ERROR: DimensionMismatch("arrays could not be broadcast to a common size") I expected it to give something like Any[ [3,4] ] because x[3] == [3,4] # => true is...

julia @printf changes my variable

I find difficult to format numbers with Julia : b = 1.111111 bb = @printf "test : %5.2f" b bb test : 1.11 That is fine. using PyPlot annotate(@printf "test : %5.2f" b, xy=[1;1]) test : type: non-boolean (Array{Bool,1}) used in boolean context while loading In[16], in expression starting on...

How do I check if a method exists for a particular type?

UPDATE: Thanks to @rickhg12s for pointing out that it appears I may have stumbled upon a bug. method_exists(<, (MyType, MyType)) is returning true while method_exists(isless, (MyType, MyType)) is returning false. I'm on v0.3.x but @rickhg12s is on the nightly build of v0.4, so I'll file an issue. How do I...

Julia parallel programming - Making existing function available to all workers

I am faced with the following problem: I have a function called TrainModel that runs for a very long time on a single thread. When it finishes computing, it returns a function as an output argument, let's call it f. When I enquire the type of this f, Julia returns:...

Passing a pointer to struct as an argument in Julia

I have a type definition corresponding to a C-struct as follows: type fakeCStruct a::Uint8; b::Uint32; end var=fakeCStruct(3,4); How can I pass a pointer to this type as an input argument (i.e. struct CStruct *) for a c-function in ccall? The old documentation (v0.3) suggest using &var in the input argument...

Julia's dictionary method `haskey` returning false when key is present

I am new to Julia and I am not sure why the last line evaluates to false: type Point{T} x::T y::T end D = [Point(1.,2.) => 42] haskey(D, Point(1., 2.)) #False! Clearly the key exists so what's going on here!? Edit. If I don't use a class Point, it works...

Julia way of searching tokens in integer arrays

Let's say I have buffer=Int[1,2,3,2,3] and token=[2,3]. Is there any preferred way of searching the occurrence of token in buffer to find [2,4] as the answer. Or, perhaps, is there any split equivalent function for the integer arrays in julia? (I know how I can perform this operation using 2...

Short circuit evaluation causing an invalid assignment location error

The docs for Julia indicate that a valid short-cut to writing out an if statement is the syntax <cond> && <statement> I've used this a lot for error messages, e.g. length(x) < N && error("x is too short"), and it works as expected. However, the following does not work: x...

Julia: @fastmath not defined

function init!(u) n = length(u) dx = 1.0 / (n-1) @fastmath @inbounds @simd for i in 1:n u[i] = sin(2pi*dx*i) end end when I execute above function in IJulia, it prompts below texts: @fastmath not defined ...

Analytical solution for Linear Regression using Python vs. Julia

Using example from Andrew Ng's class (finding parameters for Linear Regression using normal equation): With Python: X = np.array([[1, 2104, 5, 1, 45], [1, 1416, 3, 2, 40], [1, 1534, 3, 2, 30], [1, 852, 2, 1, 36]]) y = np.array([[460], [232], [315], [178]]) θ = ((np.linalg.inv(X.T.dot(X))).dot(X.T)).dot(y) print(θ) Result: [[...

Check whether a symbol can be safely evaluated

I have a string x. I think that x is a string representation of a type that is a subtype of Number. For example, x might take the value "Float64". I could check this using: eval(parse(x)) <: Number However, it is possible that x contains something dangerous, like some variant...

After building julia from source, what's safe to delete?

I was able to build it on a tiny computer, but the result now takes up ~ 1 GB of the 1.3 GB I had free. Most of this is in the /deps folder -- this is safe to delete after the build, correct?

How to construct the POE ensemble in julia

I'm having a trouble in building the POE ensemble in julia. I am following this paper and part of this other paper. In julia, I calculate: X = randn(dim, dim) Q, R = qr(X) Q = Q*diagm(sign(diag(R))) ij = (irealiz-1)*dim phases_ens[1+ij:ij+dim] = angle(eigvals(Q)) where dim is the matrix dimension and...

The ternary operator in a one-line function

In Julia, I might want to write a function that returns 0 if the input is less than 1, or returns 2 if the input is greater than or equal to 1. This is a pretty simple function, and the verbosity of a five-line if else construct is probably excessive....

What is the equation used in R's ccf and Julia's crosscor?

I've been scratching my head a lot about this. Now, except for the fact that Julia gives out a seemingly backwards result with respect to the lags julia> crosscor([1,2,3,4], [1,2,3,1])' 1x7 Array{Float64,2}: -0.30339 0.0 0.64049 0.13484 -0.37081 -0.40452 0.30339 > print(ccf(c(1,2,3,4), c(1,2,3,1), type="correlation", plot=F)) Autocorrelations of series ‘X’, by lag...

Parametric Type Creation

I'm struggling to understand parametric type creation in julia. I know that I can create a type with the following: type EconData values dates::Array{Date} colnames::Array{ASCIIString} function EconData(values, dates, colnames) if size(values, 1) != size(dates, 1) error("Date/data dimension mismatch.") end if size(values, 2) != size(colnames, 2) error("Name/data dimension mismatch.") end new(values,...

How to display a type alias instead of a parametric type in error messages

I build a parametric type in julia: type MyType{T} x::T end and for simplicity, I build a type alias for Float64: typealias MT MyType{Float64} I now deliberately cause an error involving MT. For example: y1 = MyType(1.0) y2 = MyType(2.0) y1 + y2 will throw an error because + is...

How to upgrade Julia to a new release?

Question 1 - upgrade I'm using v"0.3.8" on Windows. I found from http://julialang.org/downloads/ Current Release (v0.3.9) I know I could download the prebuild version and install again. Is there a way to upgrade (from current installed version) to the new version? There's Pkg.update(), it runs for a long time without...

Julia metaprogramming return symbol

I'm trying to figure out how to have a quote block, when evaluated, return a symbol. See the example below. function func(symbol::Symbol) quote z = $symbol symbol end end a = 1 eval(func(:a)) #this returns :symbol. I would like it to return :a z ...

How do I switch between different versions of Julia (specifically between v0.3 and v0.4 on Ubuntu)?

I am working on some projects using Julia v0.3. However, I'd like to test my code in both v0.3 and v0.4 (since some of the people that are going to be using it are already using v0.4). I'm running Ubuntu 14.04 and have installed Julia using apt-get. I know v0.4...

Powering a Math constant in Julia is slow

I'm pretty sure this has to be a bug... Ok, so basically, when I pass a Math Constant type to the power (^) function and iterate it several times... The loop is really slow and uses a lot of memory allocation. The example is trivial as it doesnt produce any...

Constructors in Julia: initializing named fields based on the input value of other named fields

Imagine a constructor that takes two arguments and initializes 3 named fields using the values of the two arguments. Something like this: type test1 a b c test1(a,b) = new(a,b,a/b) end This works fine, but what if the value for c is not such a simple expression? What if it...

Using matplotlib's patches in julia

Using the output from a computation in julia (working in IJulia), I'd like to draw a figure using matplotlib's patches module (via Steven Johnson's PyCall and PyPlot packages). I've read several related posts on stackoverflow, but I can't seem to get a minimum working example. Could somebody post a simple...

Julia: BigFloat Normal distribution

In Julia has anyone implemented the normal distributions pdf or cdf to support arbitrary precision BigFloats. For example this code returns 0.0, when in fact the values should be slightly different. x = parse(BigFloat, "2.1") x_small = float64(x) pdf(Normal(), x) - pdf(Normal(), x_small) ...

Calling Win32 Functions From Julia

I would like to call File I/O functions (i.e. CreateFile, WriteFile etc) from julia using ccall. Do I have to indicate a library name as a parameter in ccall to call any function from win32 api? If yes, how can I determine the name of the corresponding dll?...

Populating a julia dictionary with an array of symbols

I'm getting stuck on some basics of scope in Julia expressions. Can someone help tell me what is going wrong inside the for loop below? Inside the lopp the first expression works and the second does not, though both work with variables from the global scope. x = 1 glob_obj...

Convert string argument to regular expression

Trying to get into Julia after learning python, and I'm stumbling over some seemingly easy things. I'd like to have a function that takes strings as arguments, but uses one of those arguments as a regular expression to go searching for something. So: function patterncount(string::ASCIIString, kmer::ASCIIString) numpatterns = eachmatch(kmer, string,...

How to return values from recursive function to array

function nestedLoop(depth::Integer, n::Integer, symbArr, len::Integer, k::Integer, num_arr) for i = k:len num_arr[depth-n+1] = symbArr[i] n == 1 && println(num_arr) (n > 1) && nestedLoop(depth, n-1, symbArr, len, i, num_arr) end end function combwithrep(symbArr, n::Integer) len = length(symbArr) num_arr = Array(eltype(symbArr),n) nestedLoop(n, n, symbArr, len, 1, num_arr) end @time combwithrep(["+","-","*","/"], 3)...

How do I create a recursive typealias in julia?

I would like to create a nested tuple type, that can hold itself, or the particular type it contains. So I thought: typealias NestedTuple{T} Tuple{Union(T,NestedTuple{T}),Union(T,NestedTuple{T})} However this comes up with an error LoadError: UndefVarError: NestedTuple not defined How is this kind of typealias normally done? (I am in julia 0.4)...

Resize HDF5 dataset in Julia

Is there a way to resize a chunked dataset in HDF5 using Julia's HDF5.jl? I didn't see anything in the documentation. Looking through the source, all I found was set_dims!(), but that cannot extend a dataset (only shrink it). Does HDF5.jl have the ability to enlarge an existing (chunked) dataset?...

Why 2 ^ 3 ^ 4 = 0 in Julia?

I just read a post from Quora: http://www.quora.com/Is-Julia-ready-for-production-use At the bottom, there's an answer said: 2 ^ 3 ^ 4 = 0 I tried it myself: julia> 2 ^ 3 ^ 4 0 Personally I don't consider this a bug in the language. We can add parenthesis for clarity, both...

Memory allocation in a fixed point algorithm

I need to find the fixed point of a function f. The algorithm is very simple: Given X, compute f(X) If ||X-f(X)|| is lower than a certain tolerance, exit and return X, otherwise set X equal to f(X) and go back to 1. I'd like to be sure I'm not...

How to obtain deep copies of Julia composite types?

So here is the setting. I have multiple composite types defined with their own fields and constructors. Lets show two simplified components here: type component1 x y end type component2 x y z end Now I want to define a new type such that It can save an array of...

Creating an Array of Arrays in Julia

I'm trying to create an array of arrays of a special type in Julia. For example, I want to create a list that saves lists (arrays) of integer values. I need to know how to: Initialize an (empty) list for the arrays Use append!/push! to add an array of a...

One-liner or short script to run the code inside a Jupyter notebook?

I like to develop scripts by running them piecemeal in a Jupyter (nee iJulia) notebook. However, sometimes I need to test things on a remote system and need to make a copy of just the code as a .jl file. Has anyone already written a one-liner or short script that...

Converting images from RGB to HSL and back again with julia

I have been trying to open some RGB images, view the data as a 2D array of HSL pixels, manipulate pixels in HSL space, convert back to RGB and write manipulated image to file. However I don't quite understand how the conversions in the (awesome) julia packages Color and Images...