<Space> to send the current line to the interpreter.
\<Space> to send the current line to the interpreter and keep the cursor on the current line.
\q to send the quit command to the interpreter.
<Space> to send a selection of text to the interpreter.
\p to send from the line to the end of paragraph.
\b to send block of code between the two closest marks.
\f to send the entire file to the interpreter.
\m to send the text in the following motion to the interpreter. For example
\miw would send the selected word.
chamar Julia dentro do R:JuliaCall::julia_console
8.1 Básico
code/jl-introducao.jl
# ----------# básico1+12+22*24/2"Hello World"print("Hello World")# adiciona nova linha na telaprintln("Hello World")# ; ponto e vírgula no final do comando não mostra o resultado2*2;# resetar o ambiente de trabalhoworkspace()# ----------# pacotes# habilitar instalador de pacotesusing Pkg# instalar pacotes DataFramesPkg.add("DataFrames")# habilitar DataFramesusing DataFrames# sintax Pkg.[comando]# exemploDataFrames.groupby# ----------# help# help com ?[comando]?sort?DataFrames?DataFrames.describe# ] para entrar no help do pacote Pkg]# help retorna todas as funçõeshelp # ?[função] retorna o help da função de determinado pacote?rm # backspace retorna para o help geral do julia`backspace`# ----------# unicode# \alpha \beta \pi α =2β =3α * βπ# ----------# variáveisnova_var ="Hello World"# podem ser atualizadasnova_var ="Hello World - version updated "nova_var2 ="Algum texto"nova_var * nova_var2# tipo de variáveltypeof(nova_var)typeof(α)# ----------# operadores aritiméticos# ordem: / * + -2+5-6/2*3(2+5) - (6/2) *36/2*3# ----------# comentários# para uma única linha, ou """ para várias linhas, até terminar com """#= ou mesmouma forma mais simples=## ----------# forma correta de nomear variáveis# variáveis devem começar com letrasa ="essa é uma variável"a1 ="também um um bom nome"# var_name@ não é permitido# quote, e outros nomes reservados não são permitidos# ----------# Arrays # arrays são escritos com: [,]a1 = [1, 2, 3, 4, 5]# floata2 = [1, 2.0, 3, 4, 5]s1 = ["I", "Love", "Julia"]s1[1]s1[2]s1[3]# merge[a1, a2]# array de funçõesf1 = [print, println, printstyled]# mistura tiposa3 = [1, 2.0, "Julia"]# determinar o tipotype_int = Int64[1, 2, 3, 4, 5]type_string = String["I", "Love", "Julia"]# duas dimensõesarray_2d = [1234; 5678]# selecinar sub-arraysarray_2d[:,2]array_2d[1,:]array_rand =rand(3)array_rand_2d =rand(3, 3)# ----------# ranges1:10collect(1:10)# início, intervalor, fimcollect(1.5:.5:5.5)collect(1:10:100)collect(0:10:100)collect(100:-20:0)# selecionando o segundo elementocollect(100:-20:0)[2]collect(100:-20:0)[end-1]collect(100:-20:0)[begin:3]collect(100:-20:0)[1:3]# ----------# tuples# () parêntesist1 = (1, 2, 3, 4, 5)# arrays in [] a1 = [1, 2, 3, 4, 5]# imutáveis, diferente de arraysa1[2] =20a1# errot1[2] =20# duas dimensõest2 = ((1, 2), (3, 4))# acessar tuples de duas dimensõest2[1][2]# merget3 = (aa = (1, 2), bb = (3, 4))t4 = (cc = (5, 6))(t3, t4)# ----------# dictionary# pares de chaves e valores: eficientes# key são strings# values são intingerCars =Dict("Car1"=>1000, "Car2"=>2000, "Car3"=>3000)Cars["Car1"]# forma alternativa Cars2 =Dict(:Car1 =>1000, :Car2 =>2000, :Car3 =>3000)Cars2[:Car1]# determinado dicionário tem uma chave?haskey(Cars2, :Car3)haskey(Cars2, :Car4)delete!(Cars2, :Car1)keys(Cars2)values(Cars2)merge(Cars, Cars2)# ----------# sets# não aceita elementos duplicados, e não importa a ordemsports_brands =Set(["Adidas", "Nike" , "Puma", "Rebook"]) in("HRX", sports_brands)in("Puma", sports_brands)sports_brands_new =Set(["Adidas", "Nike" , "HRX", "Rebook"]) union(sports_brands, sports_brands_new)intersect(sports_brands, sports_brands_new)setdiff(sports_brands, sports_brands_new)push!(sports_brands, "marca_adicionada")# ----------# date and timeusing Datesnow()today()data =Date(2000, 2, 5) # YYYY-MM-DDdata_hora =DateTime(2000, 2, 5, 10, 15, 25) # YYYY-MM-DD-HH:MM:SS# extrair parte da datayear(data_hora)month(data_hora)day(data_hora)hour(data_hora)minute(data_hora)second(data_hora)dayofyear(data_hora)dayname(data_hora)Dates.format(data, "yy-mm-dd")# ou formato =Dates.format("yy-mm-dd") Dates.format(data, "yy-mm-dd")# time zonenow(UTC)# ----------# conditionalsa =10# if ?a >10 ? "Yes":"No"a >=10 ? "Yes":"No"b =20# or ||a >=10|| b <20# and && a >=10&& b <20a >=10&& b <=20if a >10print("a é maior que 10")elseif a <10print("a é menor que 10")elseprint("a é igual a 10")endcountry ="Brazil"if country =="Brazil"print("mencionou Brazil")elseprint("falou errado")end# ----------# loopsfor i in sports_brandsprint(i, " ")endfor i in sports_brandsprintln(i)endfor i in ["Adidas", "Puma", "Nike"]println(i)endfor i in"Adidas"println(i)endfor i in (1:9)println(i)endfor range in (1:9)@show rangeendfor i in1:10 j = i *10println("$(j) é multiplicação entre $(i) e 10")end# encontrar números primosfor i in1:10if i % 2==0 continue endprintln(i)enda =1while a <10println(a) a +=1end# ----------# comprehensions# loops escritos de forma mais eficientex = [i for i in1:10]x = [i *2for i in1:10]x = [i^2for i in1:10]# salvar como Sets =Set([i for i in1:10])# gerando dicionário com chaves para númerosalphabet =Dict(string(Char(x1 +64)) => x1 for x1 in1:26)# tupple array generated with comprehensions[(x, y) for x in1:3, y in1:2][x for x in1:10if x%2==0]# ----------# working with stringss1 ="I love Julia"length(s1)lastindex(s1)s1[4]s1[3:6]# combinar strings"Love"*"Julia""Love"^5string("Love ", "Julia")# dividir stringsplit(s1)split(s1, "e")split(s1, "")parse(Int64, "100")parse(Float64, "100.5")# encontrar# aspas simplesin('I', s1)occursin("love", s1)findfirst("l", s1)findfirst("love", s1)s1 =replace(s1, "love"=>"adore")# ----------# functions# forma compactaf(x) = x * xf(10)# forma compactaf(x, y) = x *2- yf(10, 12)# forma padrãofunctionmultiply(x, y) return x * yendmultiply(2, 4)functionconvert_meter_to_inch(val) return val *39.37endconvert_meter_to_inch(1.5)functionconvert_meter_to_inch(val, name ="Patron")if name =="Patron"println("Value for name is not supplied")elseprintln("Hi..", name, " The conversion value is ") end return val *39.37endconvert_meter_to_inch(2.3)convert_meter_to_inch(2.3, "Teteti")# ----------# formatting numbers and stringsusing Printfname ="Teteti"# não imprimirname ="Teteti";@printf("Hello %s", name)@sprintf("Hello %s", name)ch ='i'@printf("%c", ch)x =100@printf("Value of x is %d", x)y =100.5@printf("Value of x is %f", y)# contrar número de casas decimais@printf("Value of x is %.2f", y)# transformar em notação científicaz =1243987234@printf("%e", z)@printf("%.2e", z)# ----------# working with real word files .csvusing Pkg# instalarPkg.add("CSV")using CSVusing DataFramesmtcars =CSV.read("mtcars.csv", DataFrame)typeof(mtcars)names(mtcars)size(mtcars)# ----------# DataFramesmtcars.gearmtcars.mpgmtcars[:, "mpg"]mtcars[:, 2:5]mtcars[:, [2, 4, 6]]mtcars[1:6, [1, 2, 4, 6]]DataFrame(x = [1, 2, 3], y =4:6, z =9)DataFrame([(x =1, y =2), (x =3, y =4)])DataFrame("x"=> [1, 2], "y"=> [3, 4])DataFrame(x = Int[], y = Float64[])# o "." ponto, indicar aplicar para todas as linhasmtcars[mtcars.mpg .>=30, :]# reshape pivot_[longer or wider]stack()unstack()sort(mtcars, :mpg)nrow(mtcars)ncol(mtcars)names(mtcars)# NAdropmissing()alowmissing()disasalowmissing()completecases()# summarize datacombine(mtcars, :mpg => sum)combine(mtcars, :mpg =>sum =>:mpg_sum)transform()# combine data setsinnerjoin()leftjoin()rightjoin()outerjoin()semijoin()antijoin()vcat()hcat()# ----------# estatísticas descritivasdescribe(mtcars)describe(mtcars, :mean, :std)# ----------# files ystempwd()readdir()mkdir()cd()mkpath()isdir()# ----------# pipeusing Pkgusing Pipe:@pipe # para evitar conflito com Base.Pipeusing CSVusing DataFramesa1 = [1, 2, 3, 4, 5]@pipe a1 |>sum()sum(a1)mtcars =CSV.read("mtcars.csv", DataFrame)# group data sets e pipe |>@pipe mtcars |>filter(:cyl =>== ("6"), _) |>groupby(mtcars, :gear) |>combine(_, :mpg => sum)
9 Julia a partir do R
code/jl-JuliaCall.jl
# oficial# https://non-contradiction.github.io/JuliaCall/index.html# install.packages(c('JuliaCall'), dependencies = TRUE) library(JuliaCall)julia <-julia_setup()#> Julia version 1.7.2 at location /Applications/Julia-1.7.app/Contents/Resources/julia/bin will be used.#> Loading setup script for JuliaCall...#> Finish loading setup script for JuliaCall.## If you want to use `Julia` at a specific location, you could do the following:## julia_setup(JULIA_HOME = "the folder that contains Julia binary").## You can also set JULIA_HOME in command line environment or use `options(...)`.## Different ways of using Julia to calculate sqrt(2)julia$command("a = sqrt(2);"); julia$eval("a")julia_command("a = sqrt(2);"); julia_eval("a")julia_eval("sqrt(2)")julia_call("sqrt", 2)julia_eval("sqrt")(2)julia_assign("x", sqrt(2)); julia_eval("x")julia_assign("rsqrt", sqrt); julia_call("rsqrt", 2)2%>J% sqrt## You can use `julia$exists` as `exists` in R to test## whether a function or name exists in Julia or notjulia_exists("sqrt")julia_exists("c")## Functions related to installing and using Julia packagesjulia_install_package_if_needed("Optim")julia_installed_package("Optim")julia_library("Optim")## helpjulia_help("sqrt")# Abrir Julia dentro do R# JuliaCall::julia_console()