temospena / rnotebook Goto Github PK
View Code? Open in Web Editor NEWa compilation of R chunks
Home Page: http://web.tecnico.ulisboa.pt/~rosamfelix/r/COMPILACAO.html
a compilation of R chunks
Home Page: http://web.tecnico.ulisboa.pt/~rosamfelix/r/COMPILACAO.html
adicionar esta função útil que transforma um resultado de vector já no formato c( , , )
> names(locais62)
[1] "Name" "Lat" "Lon" "geometry"
> dput(names(locais62))
c("Name", "Lat", "Lon", "geometry")
Outra forma de atribuir lat
e lon
de um sf
#atribuir coordenadas latlon
PONTOS$Lon = st_coordinates(PONTOS)[,1] #W
PONTOS$Lat = st_coordinates(PONTOS)[,2] #Y
library(dplyr)
PONTOS60$quartis <- ntile(PONTOS60$`Cic/Hora_2019`, 4) %>%
factor(labels=c("Q1","Q2","Q3","Q4"))
table(PONTOS60$quartis)
# Q1 Q2 Q3 Q4
# 15 15 15 15
st_write(CicloviasCORRECT, "data/CicloviasCORRECT.shp", append = F)
vai fazer overwrite na shapefile existente, em vez de crashar :)
meter tudo com comentários
ctrl + shift + c
em vez de os carregar em cada chunk, ter só um require, e criar a lista das library que isto precisa para correr
exemplo de como fazer um Reprex.
copiar o que se quer fazer, e depois correr apenas a linha do reprex::
, e colar onde se quer colar
library(dplyr)
library(tidyr)
# OD matrix as long_format
df = data.frame("From" = c("A","A","A","C","C","C","B","B","B","D","D","D"),
"To" = c("C","B","D","B","D","A","D","A","C","A","C","B"),
"count" = c(7,35,7,5,9,7,3,15,3,11,5,2))
df
#colors
grid_col=c("#E31A1C","#33A02C","#FF7F00","#1F78B4") #colors paired
#plot
circlize::circos.clear()
circlize::circos.par(start.degree = start.degree, gap.after = gap.after)
circlize::chordDiagram(
df,
grid.col = grid_col,
directional = 1,
direction.type = c("diffHeight", "arrows"),
link.arr.type = "big.arrow",
diffHeight = -0.03
)
reprex::reprex(outfile = NA, si=T) #system info = true
ou então seleccionar, e no menu de Addins > Reprex > Reprex selection
exemplo, para calcular feriados nacionais, incluindo carnaval
u = "https://date.nager.at/api/v2/publicholidays/"
feriados = data.frame()
for(i in 2020:2030){
link = paste0(u, i, "/PT")
feriados1 = jsonlite::fromJSON(link) %>% filter(global == TRUE) %>% select(date, localName, fixed, type)
feriados = rbind(feriados,feriados1)
rm(feriados1)
}
com pipes.
shortcut pipes ctrl+shift+m
shortcut seta alt+-
O package mudou, e agora não é preciso declarar todos os settings no início nem nos knitr opt
.
Desde que tenha results='asis' deve funcionar
{r summary tables show, results='asis', echo=FALSE, message=FALSE, warning=FALSE}
dfSummary(df, valid.col = F, plain.ascii = FALSE, style = "grid", tmp.img.dir = "/tmp")
table(duplicated(OTHER$ID1))
# verifica se há repetidos
#separa os repetidos dos que são únicos
cuidado com fazer apenas uma ordem! pq em 1123 > F,T,F,F e em fromLast=T > T,F,F,F
table(duplicated(HACKfamilias$ID1)) #4509 em 29121 (15,4%)
HACKfamilias$duplic <- duplicated(HACKfamilias$ID1)
HACKfamilias$duplic2 <- duplicated(HACKfamilias$ID1, fromLast = T)
HACKfamilias$duplic3 <- duplicated(HACKfamilias$ID2)
HACKfamilias$duplic4 <- duplicated(HACKfamilias$ID2, fromLast = T)
table(HACKfamilias$duplic==F & HACKfamilias$duplic2==F & HACKfamilias$duplic3==F & HACKfamilias$duplic4==F) #21655 limpinhos
CORRECTid <- HACKfamilias[HACKfamilias$duplic==F & HACKfamilias$duplic2==F & HACKfamilias$duplic3==F & HACKfamilias$duplic4==F,c(1,2,3)] #temos 21655 correctos, faltam 2963 ?
ERRADOS <- anti_join(HACKfamilias[,c(1,2,3)],CORRECTid) #são 7466 que têm de ser reduzidos a 2963 ?
filtrar texto começado ou terminado por...
VIAGENSlisboa = TRIPS %>% filter(str_starts(DICOFREor11, "1106")) #variavel, padrão
Sugestão do Carlos:
código para os partial proportional odds (PPO) model e o paper respetivo (acho que pode ajudar a perceber o que eu andei aqui a fazer).
O cairo_pdf
já vem com o R. O cairo driver torna as linhas vectoriais mais arredondadas, e mais bonitas que gravar como png.
https://www.rdocumentation.org/packages/grDevices/versions/3.6.2/topics/cairo
https://www.jumpingrivers.com/blog/r-graphics-cairo-png-pdf-saving/
Dá também para exportar como svg ou ps
#gravar a imagem em PDF - correr primeiro isto
caminho = paste("pathblabla/",ponto,".pdf", sep="")
cairo_pdf(filename = caminho, onefile= T, width=11, height=5, fallback_resolution = 300))
#depois plotar
ggplot(dataframe)
#correr isto sempre para "fechar" o pdf
dev.off()
ListaAlojamentoID<-separate(ListaAlojamentoID, ID_aloj_1, into=c("IDa", "ID1"), sep="F1_", remove = F)
ERRADOS$ID1 %in% CORRECT$ID1
!(ERRADOS$ID1 %in% CORRECT$ID1) #not in
selecciona/conta os que há num vector e no outro
dar o exemplo dos modos de transporte por município
TRIPSmodemunicipio = TRIPSmode %>% pivot_wider(id_cols = c(1,2), names_from = modo, values_from = viagens)
#cols 1 e 2= origem e destino
TRIPSmodemunicipio[is.na(TRIPSmodemunicipio)] = 0
com a função dummy_columns do
library(fastDummies)
especificar diferenças para chr e num
#acrescentar o left_join por duas colunas com nomes diferentes , by=c("nomeA"="nomeB")
colocar secção antes de importar packages
the chunk r stplanr agregate
is only working with version 0.3 (not the most recent 0.5)
to downgrade, use
install_version("stplanr", version = "0.3.1", repos = "http://cran.us.r-project.org")
Bom exemplo: https://github.com/nicercode/EnvironmentalComputing
ver este diagrama:
https://easystats.github.io/correlation/index.html
#é mesmo superior?inferior?igual?
#t.test(x, y = NULL, alternative = c("two.sided", "less", "greater"), mu = 0,
# paired = FALSE, var.equal = FALSE, conf.level = 0.95)
t.test(c2018$SumCiclistas, c2017$SumCiclistas, alternative = "greater", mu = 0,
paired = T, var.equal = FALSE, conf.level = 0.95)
t.test(c2018$Mulher/c2018$SumCiclistas, c2017$Mulher/c2017$SumCiclistas, alternative = "greater", mu = 0,
paired = T, var.equal = FALSE, conf.level = 0.95)
t.test(c2018$CCapacete/c2018$SumCiclistas, c2017$CCapacete/c2017$SumCiclistas, alternative = "less", mu = 0,
paired = T, var.equal = FALSE, conf.level = 0.95)
Simplificar, usando o stplanr
library(sf)
library(stplanr)
# 1 -- Importar lista de coordenadas que estava em shp
COORD = st_read("path/centroides.shp")
# 2 -- criar linhas entre pares OD, que estão em formato long (O | D | num)
desire_lines <- od2line(LISTAOD, COORD)
# 3 -- exportar shapefile
st_write(desire_line, "linhasdesejo.shp")
#acrescentar a declaração do crs directamente ali
Destinos3825<- st_as_sf(Moradas3825,wkt = "wkttrabalho", crs=4326)
#Morans I' autocorrelação espacial
https://stats.idre.ucla.edu/r/faq/how-can-i-calculate-morans-i-in-r/
library(ape)
(ver GIS.r)
##adicionar esta maneira de ver os labels nas bolas
ggplot(dft_summary, aes(B3types, T0class)) +
geom_point(aes(size=count, colour=factor(prob)))+scale_color_manual(values = c("#00BA38", "#F8766D","#619CFF")) +
geom_text(data=dft_summary[dft_summary$count>25,],aes(label = count), size=4) +
geom_text(data=dft_summary[dft_summary$count<25,],aes(label = count), hjust=-1,vjust=-1, size=4) +
scale_size(range = c(1, 30)) + theme(legend.position="none") +
labs(title = "Types of potential cyclists", x = "Stages of Change", y = "Change class")
Many of us have been writing code for Windows and Linux (and OS X ...) for years. Construct yourself little helper functions
isLinux <- function() unname(Sys.info()["sysname"]) == "Linux"
and likewise for Windows. Then construct your path programmatically:
ourRootDir <- function() ifelse( isLinux(), "/opt/data/someThing", "D:/data")
via
datapath <- file.path( ourRootDir(), "project", "some", "where")
and afterwards all actual analysis commands will most likely be portable without change.
Among the 4200+ CRAN package, very few do not exist on all platforms.
Also, data written via save()
on one system can be loaded on another and as this is a binary format with compression, you also save a lot of time.
https://stackoverflow.com/questions/14923800/how-to-run-r-code-written-under-windows-in-linux
reclassificar valores numa variável
tabela = tabela %>% mutate(Percursos = recode(LTS, `3` = "seguro", `4` = "direto"))
melhorar o capítulo do geocoding
acrescentar o geocode do DV
#alerta para remover os que têm O=D quando se exporta a shp para correr o ORS tools no QGIS!
tendo uma coluna com A1, B5, C3, etc, de seu nome "mixed"
TABELA$characters = gsub("[0-9]+", "", TABELA$mixed)
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.