blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 327 | content_id stringlengths 40 40 | detected_licenses listlengths 0 91 | license_type stringclasses 2 values | repo_name stringlengths 5 134 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 46 values | visit_date timestamp[us]date 2016-08-02 22:44:29 2023-09-06 08:39:28 | revision_date timestamp[us]date 1977-08-08 00:00:00 2023-09-05 12:13:49 | committer_date timestamp[us]date 1977-08-08 00:00:00 2023-09-05 12:13:49 | github_id int64 19.4k 671M ⌀ | star_events_count int64 0 40k | fork_events_count int64 0 32.4k | gha_license_id stringclasses 14 values | gha_event_created_at timestamp[us]date 2012-06-21 16:39:19 2023-09-14 21:52:42 ⌀ | gha_created_at timestamp[us]date 2008-05-25 01:21:32 2023-06-28 13:19:12 ⌀ | gha_language stringclasses 60 values | src_encoding stringclasses 24 values | language stringclasses 1 value | is_vendor bool 2 classes | is_generated bool 2 classes | length_bytes int64 7 9.18M | extension stringclasses 20 values | filename stringlengths 1 141 | content stringlengths 7 9.18M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e78a06c55b81a298a20ac5274dae88d48a72fd81 | ceec3182ad1b8cf4007c90109f2948f0704bc3a8 | /HW2/BLB/final/Plotter.R | 8505028a85482406490f4484226daca2b1ec4ad8 | [
"MIT"
] | permissive | jmwerner/STA-250 | a42550ec5e8a5a1a36394525791ad75f3d019e9a | 203b442f809117d4ed0dfaeb50ed0c2ad2d08a33 | refs/heads/master | 2020-12-24T11:25:46.878804 | 2013-12-12T11:18:55 | 2013-12-12T11:18:55 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 374 | r | Plotter.R | setwd("/Users/jmwerner1123/Dropbox/GitHub/Invisible/STA250/HW2/BLB/final")
data = read.table("blb_lin_reg_data_s5_r50_SE.txt", header = TRUE)
attach(data)
pdf("SE_plot.pdf")
plot(x, ylab = "Standard Error Values", col = "#106BFFBB", pch = 16)
abline(h = mean(x), col = "RED", lwd = 2)
legend("topleft", c("Mean"), lty = c(1), lwd = c(2),col = "RED")
dev.off()
detach(data)
|
e95d0976e05d57e74bb12ea93b1b83eb4334c168 | 2cf2150a24f2eacaba639cdc7393a40650ba2d41 | /Board Game Analysis.R | 6bf121ec13923370ed7fe3bac3ff3d1163ded14d | [] | no_license | chiayunchiang/Board-Game-Analysis | 3f2fd0d5e0a93d662dbced7be9a882fa6d303cac | 2a80cbff6c416aef14a478e5c4c04ed572324e71 | refs/heads/main | 2023-06-03T07:41:59.352679 | 2021-06-19T04:09:28 | 2021-06-19T04:09:28 | 378,305,495 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 20,642 | r | Board Game Analysis.R | # Overview
# Part_1 Environment Setup
# Part_2 Quick view of dataset
# Part_3 Data Cleaning - Add new features into dataset
# Part_4 Data Visualization & Analysis
# Part_5 Not selected visualizations
# Part_1 Environment Setup
# Empty environment
rm(list=ls())
# Install funModeling, extrafont packages
install.packages("funModeling")
install.packages("extrafont")
library(extrafont)
# Please enter "y" in console in order to continue the process
# Please NOTE: It takes a few minutes to import the font
font_import()
# Load libraries
library(plotrix)
library(ggplot2)
library(moments)
library(plyr)
library(dplyr)
library(tidyr)
library(tidyverse)
library(RColorBrewer)
library(funModeling)
# Part_2 Quick view of dataset
# Import data
boardgame_df <- read.csv("bgg_db_1806.csv")
attach(boardgame_df)
# Take a look at data
head(boardgame_df,3)
# Shows the rows and columns
dim(boardgame_df)
# Check structure of the data
str(boardgame_df)
# Display the number of unique value in each column
rapply(boardgame_df,function(x)length(unique(x)))
# Check summary of the data
summary(boardgame_df)
# Calculate skewness for numeric data
skew <- apply(select(boardgame_df, min_players, max_players,
avg_time, min_time, max_time, avg_rating,
geek_rating, num_votes, age, owned,weight)
,2, skewness)
print(skew)
sd<- apply(select(boardgame_df, min_players, max_players,
avg_time, min_time, max_time, avg_rating,
geek_rating, num_votes, age, owned,weight)
,2, sd)
print(sd)
detach(boardgame_df)
# Part_3 Data Cleaning - Add new features into dataset
# Add new column to categorize data for further use
# Add new column "rank_group" & "rank_group_name" that categorized the rank
boardgame_df$rank_group <- floor((boardgame_df$rank-1)/20)
for(i in 1 : length(boardgame_df$rank_group)) {
boardgame_df$rank_group_name[i] <- paste("Rank", boardgame_df$rank_group[i]*20+1,"-", boardgame_df$rank_group[i]*20+20)
}
# Add new column "weight_group" & "weight_group_name" weight
summary(boardgame_df$weight) # notes: Max of weight = 4.905
boardgame_df$weight_group <- floor(boardgame_df$weight)
for(i in 1 : length(boardgame_df$weight_group)) {
boardgame_df$weight_group_name[i] <- paste(boardgame_df$weight_group[i],"-", boardgame_df$weight_group[i]+1)
}
# Quick view of weight v.s. age
boxplot(boardgame_df$weight~boardgame_df$age) # age=0 is not reasonable, it might indicate no info
# Frequency of age
table(boardgame_df$age)
# Add new column "age_group_name" to categorize age
for(i in 1:length(boardgame_df$age)){
if(boardgame_df$age[i]==0){
boardgame_df$age_group_name[i] <- "NA"
}
else{
if(boardgame_df$age[i] > 0 & boardgame_df$age[i] < 5){
boardgame_df$age_group_name[i] <- "Toddler~Preschool (1-4)"
}
else{
if(boardgame_df$age[i] > 4 & boardgame_df$age[i] < 12){
boardgame_df$age_group_name[i] <- "Gradeschooler (5-11)"
}
else{
if(boardgame_df$age[i] > 11 & boardgame_df$age[i] < 18){
boardgame_df$age_group_name[i] <- "Teen (12-17)"
}
else
boardgame_df$age_group_name[i] <- "Adult (18+)"
}
}
}
}
# Sort the column
boardgame_df$age_group_name <- factor(boardgame_df$age_group_name,
levels = c("NA", "Toddler~Preschool (1-4)",
"Gradeschooler (5-11)", "Teen (12-17)",
"Adult (18+)"))
# Frequency of age_group_names
table(boardgame_df$age_group_name)
# Part_4 Data Visualization & Analysis
# Generate common theme for further plotting use
common_theme <- function() {
ptcolor <- 'grey20'
theme(
plot.title=element_text(size=14, lineheight=0.8, color=ptcolor, hjust=0.5),
axis.title.x=element_text(color=ptcolor),
axis.title.y=element_text(color=ptcolor),
text=element_text(family="Comic Sans MS", face="bold"),
plot.background = element_rect(fill = "transparent", colour = NA),
axis.line = element_line(colour = "#2C3E50"),
panel.border = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_blank())
}
# Generate dataframe with rank 1-100 data for further use
boardgame_rank100 <- boardgame_df[1:100,]
# Check the year column
table(boardgame_df$year)
# select year from 1968-2018 (51 years)
select_year <- subset(boardgame_df, year>1967 & year<2018)
year_frequency <- as.data.frame(table(select_year$year))
names(year_frequency)[1] <- "year"
year_frequency
# Generate game_released_year plot
game_released_year <-
ggplot(year_frequency, aes(x =year, y = Freq, group=1))+
geom_line(col="#F39C12",size=2)+
geom_point(col="#0E6655", size=1.5)+
ggtitle("Board Game Released by Year")+
labs(x="Year", y="Count")+
theme(axis.text.x=element_text(angle=75,hjust=1))+
common_theme()
game_released_year
ggsave("game_released_year.png", game_released_year, bg = "transparent")
# Generate Frequency table of min_players
min_players_df <- as.data.frame(table(boardgame_df$min_players))
names(min_players_df)[1] <- "min_players"
min_players_df
# Generate BarPlot to show frequency table of min_palyers
ggplot(min_players_df , aes(x=min_players, y=Freq)) +
geom_bar(stat="identity",color="black", fill="blue", alpha=0.3) +
ggtitle("Count of Minimum Players") +
labs(x="Number of Minimum Players", y="Count")+
common_theme()
# Gnerate Percentage table for min_players
min_players_perc <- as.data.frame(prop.table(table(boardgame_df$min_players)))
names(min_players_perc)[1] <- "min_players_perc"
min_players_perc
# Generate BarPlot to show percentage table of min_palyers
min_players_perc_plot <-
ggplot(min_players_perc , aes(x=min_players_perc, y=Freq)) +
geom_bar(stat="identity",color="#999999", fill="#F5B7B1", alpha=0.7) +
ggtitle("Relative Frequency of Minimum Players") +
labs(x="Number of Minimum Players", y="Percentage")+
scale_y_continuous(labels = function(Freq) paste0(round(Freq, 2) * 100, "%"),breaks=seq(0,0.7,by=0.1))+
common_theme()
min_players_perc_plot
ggsave("min_players_perc_plot.png", min_players_perc_plot, bg = "transparent")
# Generate Frequency table of max_players
max_players_df <- as.data.frame(table(boardgame_df$max_players))
names(max_players_df)[1] <- "max_players"
max_players_df
# Generate BarPlot to show frequency table of max_palyers
ggplot(max_players_df , aes(x=max_players, y=Freq)) +
geom_bar(stat="identity",color="black", fill="blue", alpha=0.3) +
ggtitle("Count of Maximum Players") +
labs(x="Number of Maximum Players", y="Count")+
common_theme()
# Gnerate Percentage table for max_players
max_players_perc <- as.data.frame(prop.table(table(boardgame_df$max_players)))
names(max_players_perc)[1] <- "max_players_perc"
max_players_perc
# Generate BarPlot to show percentage table of max_palyers
max_players_perc_plot <-
ggplot(max_players_perc , aes(x=max_players_perc, y=Freq)) +
geom_bar(stat="identity",color="#999999", fill="#F5B7B1", alpha=0.7) +
ggtitle("Relative Frequency of Maximum Players") +
labs(x="Number of Maximum Players", y="Percentage")+
scale_y_continuous(labels = function(Freq) paste0(round(Freq, 2) * 100, "%"),breaks=seq(0,0.35,by=0.02))+
common_theme()
max_players_perc_plot
ggsave("max_players_perc_plot.png", max_players_perc_plot, bg = "transparent")
# Generate density plot for "weight" & "avg_time" column
# Weight density plot
weight_mean <- mean(boardgame_df$weight)
weight_density <- ggplot(boardgame_df, aes(x=weight)) +
geom_density(color="#999999", fill="#E59866", alpha=0.7)+
geom_vline(aes(xintercept=mean(weight)),
color="#A04000", linetype="dashed", size=1)+
geom_text(aes(label=paste("Mean =",round(weight_mean,1)),x=2.8, y=0.5),col='#A04000',size=4, family="Comic Sans MS")+
ggtitle("Density Plot of Difficulty")+
labs(x="Difficulty", y = "Density")+
common_theme()
weight_density
ggsave("weight_density.png", weight_density, bg = "transparent")
# avg_time density plot (remove outlier in the plot)
avg_time_density <- ggplot(boardgame_df, aes(x=avg_time)) +
geom_density(color="#999999", fill="#E59866", alpha=0.7)+
geom_vline(aes(xintercept=mean(owned)),
color="blue", linetype="dashed", size=1)+
ggtitle("Density Plot of Average Time")+
labs(x = "Average Time", y="Density")+
scale_x_continuous(breaks=seq(0,300,by=20), limits = c(0,300))+
common_theme()
avg_time_density
ggsave("avg_time_density.png", avg_time_density, bg = "transparent")
# Generate Frequency table of "age_group_name"
age_group_freq <- as.data.frame(table(boardgame_df$age_group_name))
names(age_group_freq)[1] <- "age_group_name"
age_group_freq
# Generate BarPlot to show frequency table of Age group
age_group_freq_plot <-
ggplot(subset(age_group_freq,!age_group_name %in% c("NA")), aes(x=age_group_name, y=Freq)) +
geom_bar(stat="identity",color="#999999", fill="#AF7AC5", alpha=0.7) +
ggtitle("Frequency of Age Group (All Board Games)") +
labs(x="Age Group", y="Count")+
common_theme()
age_group_freq_plot
ggsave("age_group_freq_plot.png", age_group_freq_plot, bg = "transparent")
# Category Frequency Plot (whole dataset)
# Clean "category" column
attach(boardgame_df)
clean_category <- str_trim(unlist(strsplit(str_trim(as.character(category)),",")))
clean_category
# Generate Frequency table of "category"
category_df <- as.data.frame(table(clean_category))
category_df
# Generate category barplot
category_barplot <-ggplot(category_df, aes(x=Freq, y=reorder(clean_category, Freq))) +
geom_bar(stat="identity") + ggtitle("Frequency of Board Game Category") +
labs(x="Frequency", y="Category")+
common_theme() + theme(axis.text=element_text(size=4),
axis.title=element_text(size=10,face="bold"))
# Only display first 10 in plot
top10_df <- category_df[tail(order(category_df$Freq), 10), ]
top10_df
category_freq_plot <-
ggplot(top10_df, aes(x=Freq, y=reorder(clean_category, Freq),fill=Freq)) +
geom_bar(stat="identity") + ggtitle("Frequency of Board Game Category (Overall)") +
labs(x="Frequency", y="Category")+
common_theme()+
theme(legend.title = element_blank(),legend.position='none',
axis.text.x=element_text(color='grey20', size=14),
axis.text.y=element_text(color='grey20', size=14))
category_freq_plot
ggsave("category_freq_plot.png",category_freq_plot, bg = "transparent")
detach(boardgame_df)
# Category Frequency Plot (only rank 1-100 dataset)
# The same as above process
# Clean "category" column
clean_category_rank100 <- str_trim(unlist(strsplit(str_trim(as.character(boardgame_rank100$category)),",")))
clean_category_rank100
# Generate frequency table
category_df_rank100 <- as.data.frame(table(clean_category_rank100))
category_df_rank100
# Assign dataframe for displaying only 10 data in plot
top10_df_rank100 <- category_df_rank100[tail(order(category_df_rank100$Freq), 10), ]
top10_df_rank100
# Generate rank100 category frequency plot
category_freq_plot_100 <-
ggplot(top10_df_rank100, aes(x=Freq, y=reorder(clean_category_rank100, Freq), fill= Freq)) +
geom_bar(stat="identity") + ggtitle("Frequency of Board Game Category (Top 100)") +
labs(x="Frequency", y="Category")+
common_theme() +
theme(legend.title = element_blank(),legend.position='none',
axis.text.x=element_text(color='grey20', size=14),
axis.text.y=element_text(color='grey20', size=14))
category_freq_plot_100
ggsave("category_freq_plot_100.png",category_freq_plot_100, bg = "transparent")
# Generate BoxPlot to explore the category data
# Average Rating versus Difficulty
difficulty_versus_average_rating <-
ggplot(boardgame_df, aes(x=weight_group_name, y=avg_rating, fill=weight_group_name, alpha=0.9)) +
geom_boxplot(color="#999999")+common_theme()+ggtitle("Average Rating versus Difficulty") +
labs(x="Difficulty", y="Average Rating")+
common_theme()+
theme(legend.position='none')
difficulty_versus_average_rating
ggsave("difficulty_versus_average_rating.png",difficulty_versus_average_rating, bg = "transparent")
# Designer Frequency
attach(boardgame_df)
clean_designer <- str_trim(unlist(strsplit(str_trim(as.character(designer)),",")))
designer_df <- as.data.frame(table(clean_designer))
# Remove useless value
remove_designer <- c("(Uncredited)", "Jr.","none")
designer_df <- filter(designer_df, !clean_designer %in% remove_designer)
designer_df <- designer_df[tail(order(designer_df$Freq), 10), ]
designer_df
designer_top10 <-
ggplot(designer_df, aes(x=Freq, y=reorder(clean_designer, Freq), fill= Freq)) +
geom_bar(stat="identity", color="#999999") + ggtitle("Frequency of Designer (All Board Games)") +
labs(x="Frequency", y="Designer")+
common_theme()+theme(legend.position='none')
designer_top10
ggsave("designer_top10.png",designer_top10, bg = "transparent")
# Designer Frequency rank 100
clean_designer_rank100 <- str_trim(unlist(strsplit(str_trim(as.character(boardgame_rank100$designer)),",")))
designer_df_rank100 <- as.data.frame(table(clean_designer_rank100))
designer_df_rank100 <- designer_df_rank100[tail(order(designer_df_rank100$Freq), 10), ]
designer_df_rank100
designer_top10_rank100 <-ggplot(designer_df_rank100, aes(x=Freq, y=reorder(clean_designer_rank100, Freq), fill= Freq)) +
geom_bar(stat="identity",color="#999999") + ggtitle("Frequency of Designer (Top 100 Board Games)") +
labs(x="Frequency", y="Designer")+
common_theme() + theme(legend.position='none',
axis.text.x=element_text(color='grey20', size=14),
axis.text.y=element_text(color='grey20', size=14))
designer_top10_rank100
ggsave("designer_top10_rank100.png",designer_top10_rank100, bg = "transparent")
# generate rank 1-10 designer name list
df_first_10 <- boardgame_df[1:10,]
df_first_10 <- str_trim(unlist(strsplit(str_trim(as.character(df_first_10$designer)),",")))
df_first_10
# Frequency of designer for overall board game, also highlight the designer who has game in rank 10
designer_fre_plot <-
ggplot(designer_df, aes(x=Freq, y=reorder(clean_designer, Freq),alpha=0.7)) +
geom_bar(stat="identity", color="#999999", fill=ifelse(designer_df$clean_designer %in% df_first_10,"#EC7063","#F4D03F")) +
ggtitle("Frequency of Designer (Overall Board Games)",subtitle = "Hightlight in Red for Rank 10 Designers") +
labs(x="Frequency", y="Designer")+
common_theme() + theme(legend.position='none')+
theme(legend.position='none',plot.subtitle = element_text(size=12, lineheight=0.8, color='grey20', hjust=0.5),
axis.text.x=element_text(color='grey20', size=14),
axis.text.y=element_text(color='grey20', size=14))
designer_fre_plot
ggsave("designer_fre_plot.png",designer_fre_plot, bg = "transparent")
# Top10 designer of rank 100 boardgame, highligh top10 freqency
designer_fre_plot_100 <-
ggplot(designer_df_rank100, aes(x=Freq, y=reorder(clean_designer_rank100, Freq),alpha=0.7)) +
geom_bar(stat="identity", color="#999999", fill=ifelse(designer_df_rank100$clean_designer_rank100 %in% df_first_10, "#EC7063","#F4D03F")) +
ggtitle("Frequency of Top 10 Designers (Top 100 Board Games)",subtitle = "Hightlight in Red for Rank 10 Designers") +
labs(x="Frequency", y="Designer")+
common_theme() +
theme(legend.position='none',plot.subtitle = element_text(size=12, lineheight=0.8, color='grey20', hjust=0.5),
axis.text.x=element_text(color='grey20', size=14),
axis.text.y=element_text(color='grey20', size=14))
designer_fre_plot_100
ggsave("designer_fre_plot_100.png",designer_fre_plot_100, bg = "transparent")
# Owned frequency
boardgame_df %>%
arrange(desc(owned)) %>%
slice(1:10)%>%
ggplot(., aes(x=owned, y=reorder(names,owned)))+
geom_bar(stat='identity')+
common_theme()
# Owned frequency rank100
owned_freq_plot <-
boardgame_rank100 %>%
arrange(desc(owned)) %>%
slice(1:10)%>%
ggplot(., aes(x=owned, y=reorder(names,owned)))+
geom_bar(stat='identity', color="#999999", fill="#EB984E", alpha=0.7)+
ggtitle("Frequency of Owned (Top 100 Board Games) ")+
labs(x="Owned", y="Board Game Name")+
common_theme()+
theme(axis.text.x=element_text(color='grey20', size=14),
axis.text.y=element_text(color='grey20', size=14))
owned_freq_plot
ggsave("owned_freq_plot.png",owned_freq_plot, bg = "transparent")
# correlation between factors
correlation_table(data=boardgame_df, target="owned")
#correlation_table(data=boardgame_df, target="geek_rating")
#correlation_table(data=boardgame_df, target="avg_rating")
#correlation_table(data=boardgame_df, target="weight")
#-------------------------------------------------------------------------
# Part_5 Not selected visualizations
# Visualization and exploration (Not selected to include in the final ppt)
# Age density plot
age_density <- ggplot(boardgame_df, aes(x=age)) +
geom_density(color="black", fill="blue", alpha=0.3)+
geom_vline(aes(xintercept=mean(age)),
color="blue", linetype="dashed", size=1)+
ggtitle("Density Plot of Age")+
common_theme()
age_density
# Avg rating density plot
avg_rating_density <- ggplot(boardgame_df, aes(x=avg_rating)) +
geom_density(color="black", fill="blue", alpha=0.3)+
geom_vline(aes(xintercept=mean(avg_rating)),
color="blue", linetype="dashed", size=1)+
ggtitle("Density Plot of Average Rating")+
common_theme()
avg_rating_density
# Geek rating density plot
geek_rating_density <- ggplot(boardgame_df, aes(x=geek_rating)) +
geom_density(color="black", fill="blue", alpha=0.3)+
geom_vline(aes(xintercept=mean(geek_rating)),
color="blue", linetype="dashed", size=1)+
ggtitle("Density Plot of Geek Rating")+
common_theme()
geek_rating_density
# owned density plot
owned_density <- ggplot(boardgame_df, aes(x=owned)) +
geom_density(color="black", fill="blue", alpha=0.3)+
geom_vline(aes(xintercept=mean(owned)),
color="blue", linetype="dashed", size=1)+
ggtitle("Density Plot of Owned")+
common_theme()
owned_density
# Generate Frequency table of min_players for rank100
min_players_df_100 <- as.data.frame(table(boardgame_rank100$min_players))
names(min_players_df_100)[1] <- "min_players"
min_players_df_100
# Generate BarPlot to show frequency table of min_palyers for rank100
ggplot(min_players_df_100 , aes(x=min_players, y=Freq)) +
geom_bar(stat="identity",color="black", fill="blue", alpha=0.3) +
ggtitle("Frequency of min players") +
labs(x="min_players", y="Count")+
common_theme()
# Generate Frequency table of max_players for rank100
max_players_df_100 <- as.data.frame(table(boardgame_rank100$max_players))
names(max_players_df_100)[1] <- "max_players"
max_players_df_100
# Generate BarPlot to show frequency table of max_palyers for rank100
ggplot(max_players_df_100 , aes(x=max_players, y=Freq)) +
geom_bar(stat="identity",color="black", fill="blue", alpha=0.3) +
ggtitle("Frequency of Max Players for Rank100") +
labs(x="Age Group", y="Count")+
common_theme()
# Difficulty versus Age Group
ggplot(subset(boardgame_df, !age_group_name %in% c("NA")), aes(x=age_group_name, y=weight, fill=age_group_name)) +
geom_boxplot()+common_theme()+ggtitle("Difficulty versus Age Group") +
labs(x="Age", y="Difficulty")+
theme(legend.position='none')
# Geek Rating versus Difficulty
ggplot(boardgame_df, aes(x=weight_group_name, y=geek_rating, fill=weight_group_name)) +
geom_boxplot()+common_theme()+ggtitle("Geek Rating versus Difficulty") +
labs(x="Difficulty", y="Geek Rating")+
theme(legend.position='none')
# Rank 100 Difficulty versus Rank group
difficulty_versus_rankgroup <-
ggplot(boardgame_rank100, aes(x=rank_group_name, y=weight, fill=rank_group_name, alpha=0.7)) +
geom_boxplot()+common_theme()+ggtitle("Difficulty versus Rank Group") +
labs(x="Rank Group", y="Difficulty")+
common_theme()+
theme(legend.position='none')
difficulty_versus_rankgroup
# Generate Frequency table of "age_group_name" for rank100
age_group_freq_100 <- as.data.frame(table(boardgame_rank100$age_group_name))
names(age_group_freq_100 )[1] <- "age_group_name"
age_group_freq_100
# Generate BarPlot to show frequency table of Age group for rank100
age_group_freq_100_plot <-
ggplot(subset(age_group_freq_100 ,!age_group_name %in% c("NA")), aes(x=age_group_name, y=Freq)) +
geom_bar(stat="identity",color="#999999", fill="#AF7AC5", alpha=0.7) +
ggtitle("Frequency of Age Group (Top 100 Board Games)") +
labs(x="Age Group", y="Count")+
common_theme()
age_group_freq_100_plot
|
dd3ad2e00dcb422276c6772e3dfc2ec2be315f7a | 479a7427ad45156fe9950588f6071ba102b949fe | /Random Forests.R | 10ce6aa80d7cf55b8635d46e335afe07f7308fbc | [] | no_license | jaldecoa1/Practice | 62e67ce00cd3e8c31690037a6cfeae5bab306971 | b3e53b9bbaa6312e5c47793ed42c8a72cbe8a96a | refs/heads/master | 2022-11-19T07:47:03.975975 | 2020-07-19T23:42:05 | 2020-07-19T23:42:05 | 280,458,534 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 3,882 | r | Random Forests.R | # Random forests
library(ggplot2)
library(randomForest)
# Get data
url <- "http://archive.ics.uci.edu/ml/machine-learning-databases/heart-disease/processed.cleveland.data"
data <- read.csv(url, header = FALSE)
# Clean up data
colnames(data) <- c(
"age",
"sex",
"cp",
"trestbps",
"chol",
"fbs",
"restecg",
"thalach",
"exang",
"oldpeak",
"slope",
"ca",
"thal",
"hd"
)
data[data == "?"] <- NA
data[data$sex == 0,]$sex <- "F"
data[data$sex == 1,]$sex <- "M"
data$sex <- as.factor(data$sex)
data$cp <- as.factor(data$cp)
data$fbs <- as.factor(data$fbs)
data$restecg <- as.factor(data$restecg)
data$exang <- as.factor(data$exang)
data$slope <- as.factor(data$slope)
data$ca <- as.integer(data$ca)
data$ca <- as.factor(data$ca)
data$thal <- as.integer(data$thal)
data$thal <- as.factor(data$thal)
data$hd <- ifelse(test=data$hd == 0, yes="Healthy", no="Unhealthy")
data$hd <- as.factor(data$hd)
# Since we're going to be randomly sampling, set the
# set the seed for the random number generator so that
# we can reporduce our results.
set.seed(42)
# Impute values for the NAs in the dataset with rfImput()
# This number should get smaller if our estimates are improving.
# Since they don't, we can assume that it's as good as it's
# going to get.
data.imputed <- rfImpute(hd ~ ., data = data, iter = 6)
# Build random forest with randomForest() function
model <- randomForest(hd ~ ., data=data.imputed, proximity = TRUE)
# To see if 500 trees is enough for optimal classification
# we can plot the error rate
oob.error.data <- data.frame(
Trees=rep(1:nrow(model$err.rate), times=3),
Type=rep(c("OOB", "Healthy", "Unhealthy"), each=nrow(model$err.rate)),
Error=c(model$err.rate[,"OOB"],
model$err.rate[,"Healthy"],
model$err.rate[,"Unhealthy"]))
ggplot(data=oob.error.data, aes(x=Trees, y=Error)) +
geom_line(aes(color=Type))
## Will adding more trees reduce the error rate? To test this
## we will create a random forest with more trees.
model <- randomForest(hd ~ ., data = data.imputed, ntree = 1000, proximity = TRUE)
# Plot error rates
ob.error.data <- data.frame(
Trees=rep(1:nrow(model$err.rate), times=3),
Type=rep(c("OOB", "Healthy", "Unhealthy"), each=nrow(model$err.rate)),
Error=c(model$err.rate[,"OOB"],
model$err.rate[,"Healthy"],
model$err.rate[,"Unhealthy"]))
ggplot(data=oob.error.data, aes(x=Trees, y=Error)) +
geom_line(aes(color=Type))
## Now we need to make sure we are considering the optimal
## number of variables at each internal node in the tree
# Create an empty vector that can hold 10 values
oob.values <- vector(length = 10)
# Create a loop that tests different numbers of variables
# at each step.
for(i in 1:10) {
temp.model <- randomForest(hd ~ ., data=data.imputed, mtry=i, ntree=1000)
oob.values[i] <- temp.model$err.rate[nrow(temp.model$err.rate),1]
}
## Create an MDS plot
distance.matrix <- dist(1-model$proximity)
mds.stuff <- cmdscale(distance.matrix, eig=TRUE, x.ret=TRUE)
mds.var.per <- round(mds.stuff$eig/sum(mds.stuff$eig)*100, 1)
# Format MDS data for ggplot2 and plot graph
mds.values <- mds.stuff$points
mds.data <- data.frame(Sample=rownames(mds.values),
X = mds.values[,1],
Y = mds.values[,2],
Status = data.imputed$hd)
ggplot(data = mds.data, aes(x = X, y = Y, label = Sample)) +
geom_text(aes(color = Status)) +
theme_bw() +
xlab(paste("MDS1 - ", mds.var.per[1], "%", sep = "")) +
ylab(paste("MDS2 - ", mds.var.per[2], "%", sep = "")) +
ggtitle("MDS plot using (1 - Random Forest Proximities)")
|
5fe7e63a3ae82eb581b651d9ef32a3e5e3c42755 | 0754603b7cdad0ceca3ee2a72ce76b90e85f83f6 | /man/get_attr_names.Rd | 54a8c6cc2f6d9c9476a746e172d3715132fb9123 | [] | no_license | cran/hdfqlr | 63da901e49d5b907f600b5fecdd36e66628f0b94 | 0700e6fd98a347d21642efe735af981fb7379549 | refs/heads/master | 2021-07-02T20:26:59.782690 | 2021-06-11T03:50:02 | 2021-06-11T03:50:02 | 236,610,578 | 0 | 0 | null | null | null | null | UTF-8 | R | false | true | 411 | rd | get_attr_names.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/basic.r
\name{get_attr_names}
\alias{get_attr_names}
\title{Get HDF Attribute Names}
\usage{
get_attr_names(path)
}
\arguments{
\item{path}{The path of the dataset or group from which to
retrieve attribute names.}
}
\value{
A vector of attribute names.
}
\description{
Get HDF Attribute Names
}
\keyword{internal}
|
8f761e0ca442041fb760159b36ef5ffaf5a11e4b | 34b1ab46a70fe81143874a40d6493c0254f1e5c9 | /R/xgbfi_R_test.R | b8c947721f0cfbeb62740b66c26c65d443b86235 | [] | no_license | yama1968/Spikes | 5f974a20812dbd88f789cabf7720826d358f8e76 | 498b0cacfc23627ecee743f012a6fda6451cda7f | refs/heads/master | 2021-06-06T00:33:33.637745 | 2020-11-14T18:49:25 | 2020-11-14T18:49:25 | 29,531,065 | 2 | 0 | null | 2020-11-12T21:13:21 | 2015-01-20T13:29:35 | Jupyter Notebook | UTF-8 | R | false | false | 374 | r | xgbfi_R_test.R | library(xgboost)
library(Ecdat)
# devtools::install_github("RSimran/RXGBfi")
library(RXGBfi)
data(Icecream)
train.data <- data.matrix(Icecream[,-1])
bst <- xgboost(data = train.data, label = Icecream$cons, max.depth = 3, eta = 1, nthread = 2,
nround = 2, objective = "reg:linear")
features <- names(Icecream[,-1])
xgb.fi(model = bst, features = features)
|
5050dffdec4744004b37b929143810089eba7739 | 9bdef83f28b070321ba27709d2c7ec028474b5c3 | /R/install.R | 94d5692079fbee8eac40e5b149c510ffa5ed7817 | [] | no_license | antagomir/scripts | 8e39ce00521792aca1a8169bfda0fc744d78c285 | c0833f15c9ae35b1fd8b215e050d51475862846f | refs/heads/master | 2023-08-10T13:33:30.093782 | 2023-05-29T08:19:56 | 2023-05-29T08:19:56 | 7,307,443 | 10 | 15 | null | 2023-07-19T12:36:45 | 2012-12-24T13:17:03 | HTML | UTF-8 | R | false | false | 1,219 | r | install.R | # biclust requires installing curl and setting curl-config path
# see locate libcurl and locate curl-config and
# http://www.omegahat.org/RCurl/FAQ.html
#~/local/bin/curl-7.20.1> ./configure --prefix=/users/lmlahti/bin
# make && make install
# After adding path to .cshrc
#(line: set path=($path /home/lmlahti/bin/curl-7.21.3)
# and "source .cshrc"
# and isntalling "libcurl-ocaml-dev" with synaptic
#I got RCurl installed with:
#~/local/R/R-2.12.0/bin/R CMD INSTALL ~/local/R/packages/RCurl_1.5-0.tar.gz
# GITHUB API limit exceeded. See if number of pkgs can be reduceed.
#source('http://www.bioconductor.org/biocLite.R')
#update.packages()
#biocLite()
install.packages("BiocManager")
library(BiocManager)
source("installation_pkgs.R")
pkgs <- c(cran.pkgs, bioc.pkgs)
suppressUpdate <- TRUE
update <- FALSE
for (pkg in pkgs) {
if( !require(pkg) ){
print(pkg)
BiocManager::install(pkg, suppressUpdates = suppressUpdate, update=update)
}
}
library(extrafont, font_import())
# options(repos = c(getOption("repos", rstan = "http://wiki.rstan-repo.googlecode.com/git/")))
library("devtools")
source("install_github.R")
# source("install_universe.R")
#upgrade.packages()
update.packages(checkBuilt=TRUE) |
fdcdbd471110a5d532e3b8ac123d980acf300c96 | 61a3978c8068d4a4079388e7d4353d15afe1606b | /R/Dists.R | bb68897ed65332f5a48356b76de405b45575119b | [] | no_license | cran/SuppDists | ce29b265a053861a2d925ed79620526bf8110c74 | 28e891aa9bc0268838ba19c37502420ed0e255a7 | refs/heads/master | 2022-01-30T20:23:33.023947 | 2022-01-03T17:10:06 | 2022-01-03T17:10:06 | 17,693,811 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 32,990 | r | Dists.R |
dFriedman <-
function (x, r, N, log = FALSE)
{
M <- max(length(x), length(r), length(N))
x <- rep(x, length.out = M)
r <- rep(r, length.out = M)
N <- rep(N, length.out = M)
rho <- rep(FALSE, length.out = M)
value <- .C(`dFriedmanR`, as.double(x), as.integer(r), as.integer(N),
as.integer(M), as.integer(rho), val = double(M),PACKAGE="SuppDists")$val
if (log == TRUE)
value <- log(value)
value
}
dghyper <-
function (x, a, k, N, log = FALSE)
{
M <- max(length(x), length(a), length(k), length(N))
x <- rep(x, length.out = M)
a <- rep(a, length.out = M)
k <- rep(k, length.out = M)
N <- rep(N, length.out = M)
value <- .C(`dghyperR`, as.integer(x), as.double(a), as.double(k),
as.double(N), as.integer(M), val = double(M),PACKAGE="SuppDists")$val
if (log == TRUE)
value <- log(value)
value
}
dinvGauss <-
function (x, nu, lambda, log = FALSE)
{
N <- max(length(x), length(nu), length(lambda))
x <- rep(x, length.out = N)
nu <- rep(nu, length.out = N)
lambda <- rep(lambda, length.out = N)
value <- .C(`dinvGaussR`, as.double(x), as.double(nu), as.double(lambda),
as.integer(N), lambda = double(N),PACKAGE="SuppDists")$lambda
if (log == TRUE)
value <- log(value)
value
}
dJohnson <-
function (x, parms, log = FALSE)
{
tfun <- function(x) if (x == "SN")
1
else if (x == "SL")
2
else if (x == "SU")
3
else 4
vecFromList <- function(item, aList) {
if (!is.list(aList[[1]]))
return(aList[[item]])
else {
tVec <- vector(length = 0)
for (i in 1:length(aList)) {
tVec <- append(tVec, (aList[[i]])[[item]])
}
}
tVec
}
gamma <- vecFromList(1, parms)
delta <- vecFromList(2, parms)
xi <- vecFromList(3, parms)
lambda <- vecFromList(4, parms)
type <- vecFromList(5, parms)
type <- sapply(type, tfun)
N <- max(length(gamma), length(x))
x <- rep(x, length.out = N)
gamma <- rep(gamma, length.out = N)
delta <- rep(delta, length.out = N)
xi <- rep(xi, length.out = N)
lambda <- rep(lambda, length.out = N)
type <- rep(type, length.out = N)
value <- .C(`dJohnsonR`, as.double(x), as.double(gamma),
as.double(delta), as.double(xi), as.double(lambda), as.integer(type),
as.integer(N), val = double(N),PACKAGE="SuppDists")$val
if (log == TRUE)
value <- log(value)
value
}
dKendall <-
function (x, N, log = FALSE)
{
M <- max(length(x), length(N))
x <- rep(x, length.out = M)
N <- rep(N, length.out = M)
value <- .C(`dKendallR`, as.integer(N), as.double(x), as.integer(M),
val = double(M),PACKAGE="SuppDists")$val
if (log == TRUE)
value <- log(value)
value
}
dKruskalWallis <-
function (x, c, N, U, log = FALSE)
{
M <- max(length(x), length(c), length(N), length(U))
x <- rep(x, length.out = M)
c <- rep(c, length.out = M)
n <- rep(N, length.out = M)
U <- rep(U, length.out = M)
Ns <- rep(FALSE, length.out = M)
value <- .C(`dKruskalWallisR`, as.double(x), as.integer(c),
as.integer(n), as.double(U), as.integer(Ns), as.integer(M),
val = double(M),PACKAGE="SuppDists")$val
if (log == TRUE)
value <- log(value)
value
}
dmaxFratio <-
function (x, df, k, log = FALSE)
{
if (log == TRUE)
p <- exp(p)
N <- max(length(x), length(df), length(k))
x <- rep(x, length.out = N)
df <- rep(df, length.out = N)
k <- rep(k, length.out = N)
.C(`dmaxFratioR`, as.double(x), as.integer(df), as.integer(k),
as.integer(N), val = double(N),PACKAGE="SuppDists")$val
}
dNormScore <-
function (x, c, N, U, log = FALSE)
{
M <- max(length(x), length(c), length(N), length(U))
x <- rep(x, length.out = M)
c <- rep(c, length.out = M)
n <- rep(N, length.out = M)
U <- rep(U, length.out = M)
Ns <- rep(TRUE, length.out = M)
value <- .C(`dKruskalWallisR`, as.double(x), as.integer(c),
as.integer(n), as.double(U), as.integer(Ns), as.integer(M),
val = double(M),PACKAGE="SuppDists")$val
if (log == TRUE)
value <- log(value)
value
}
dPearson <-
function (x, N, rho = 0, log = FALSE)
{
M <- max(length(x), length(rho), length(N))
x <- rep(x, length.out = M)
rho <- rep(rho, length.out = M)
N <- rep(N, length.out = M)
value <- .C(`dcorrR`, as.double(x), as.double(rho), as.integer(N),
as.integer(M), val = double(M),PACKAGE="SuppDists")$val
if (log == TRUE)
value <- log(value)
value
}
dSpearman <-
function (x, r, log = FALSE)
{
M <- max(length(x), length(r))
x <- rep(x, length.out = M)
r <- rep(r, length.out = M)
N <- rep(2, length.out = M)
rho <- rep(TRUE, length.out = M)
value <- .C(`dFriedmanR`, as.double(x), as.integer(r), as.integer(N),
as.integer(M), as.integer(rho), val = double(M),PACKAGE="SuppDists")$val
if (log == TRUE)
value <- log(value)
value
}
JohnsonFit <-
function (t, moment = "quant")
{
firstChar=substring(moment,1,1)
if (firstChar=="f") {
mom <- moments(t)
mu <- mom[[1]]
sigma <- mom[[2]]
skew <- mom[[3]]
kurt <- mom[[4]]
value <- .C(`JohnsonMomentFitR`, as.double(mu), as.double(sigma),
as.double(skew), as.double(kurt), gamma = double(1),
delta = double(1), xi = double(1), lambda = double(1),
type = integer(1),PACKAGE="SuppDists")
}
else if (firstChar=="u") {
mu<-t[1]
sigma<-sqrt(t[2])
skew<-t[3]/sigma^3
kurt<-(t[4]/t[2]^2)-3
value <- .C(`JohnsonMomentFitR`, as.double(mu), as.double(sigma),
as.double(skew), as.double(kurt), gamma = double(1),
delta = double(1), xi = double(1), lambda = double(1),
type = integer(1),PACKAGE="SuppDists")
}
else if (firstChar=="q") {
input <- quantile(t, probs = c(0.05, 0.206, 0.5, 0.794,
0.95), names = FALSE)
x5 <- input[[1]]
x20.6 <- input[[2]]
x50 <- input[[3]]
x79.4 <- input[[4]]
x95 <- input[[5]]
value <- .C(`JohnsonFitR`, as.double(x95), as.double(x79.4),
as.double(x50), as.double(x20.6), as.double(x5),
gamma = double(1), delta = double(1), xi = double(1),
lambda = double(1), type = integer(1),PACKAGE="SuppDists")
}
else return(NA)
types <- c("SN", "SL", "SU", "SB")
list(gamma = value$gamma, delta = value$delta, xi = value$xi,
lambda = value$lambda, type = types[value$type])
}
makeStatList <-
function (head, mn, med, var, mod, third, fourth, dig)
{
sd <- sqrt(var)
skew <- sign(third) * abs(third)/sd^3
kurt <- -3 + fourth/var^2
pskew <- (mn - mod)/sd
if (dig > 0) {
mn <- round(mn, digits = dig)
med <- round(med, digits = dig)
mod <- round(mod, digits = dig)
var <- round(var, digits = dig)
sd <- round(sd, digits = dig)
third <- round(third, digits = dig)
fourth <- round(fourth, digits = dig)
pskew <- round(pskew, digits = dig)
skew <- round(skew, digits = dig)
kurt <- round(kurt, digits = dig)
}
theList <- list(Mean = mn, Median = med, Mode = mod, Variance = var,
SD = sd, ThirdCentralMoment = third, FourthCentralMoment = fourth,
PearsonsSkewness...mean.minus.mode.div.SD = pskew, Skewness...sqrtB1 = skew,
Kurtosis...B2.minus.3 = kurt)
c(head, theList)
}
moments <-
function (x)
{
N <- length(x)
v <- ((N - 1)/N) * var(x)
sigma <- sqrt(v)
m3 <- (sum((x - mean(x))^3))/N
skew <- m3/sigma^3
m4 <- (sum((x - mean(x))^4))/N
kurt <- (m4/v^2) - 3
c(mean = mean(x), sigma = sigma, skew = skew, kurt = kurt)
}
normOrder <-
function (N)
{
N <- if (length(N) > 1)
length(N)
else N
M <- N%/%2
value <- .C(`normOrdR`, val = double(M), as.integer(N), as.integer(M),PACKAGE="SuppDists")$val
if (0 == N%%2)
c(-value, rev(value))
else c(-value, 0, rev(value))
}
pFriedman <-
function (q, r, N, lower.tail = TRUE, log.p = FALSE)
{
M <- max(length(q), length(r), length(N))
q <- rep(q, length.out = M)
r <- rep(r, length.out = M)
N <- rep(N, length.out = M)
rho <- rep(FALSE, length.out = M)
if (lower.tail == TRUE) {
value <- .C(`pFriedmanR`, as.double(q), as.integer(r),
as.integer(N), as.integer(M), as.integer(rho), val = double(M),PACKAGE="SuppDists")$val
}
else {
value <- .C(`uFriedmanR`, as.double(q), as.integer(r),
as.integer(N), as.integer(M), as.integer(rho), val = double(M),PACKAGE="SuppDists")$val
}
if (log.p == TRUE)
value <- log(value)
value
}
pghyper <-
function (q, a, k, N, lower.tail = TRUE, log.p = FALSE)
{
M <- max(length(q), length(a), length(k), length(N))
q <- rep(q, length.out = M)
a <- rep(a, length.out = M)
k <- rep(k, length.out = M)
N <- rep(N, length.out = M)
if (lower.tail == TRUE) {
value <- .C(`pghyperR`, as.integer(q), as.double(a),
as.double(k), as.double(N), as.integer(M), val = double(M),PACKAGE="SuppDists")$val
}
else {
value <- .C(`ughyperR`, as.integer(q), as.double(a),
as.double(k), as.double(N), as.integer(M), val = double(M),PACKAGE="SuppDists")$val
}
if (log.p == TRUE)
value <- log(value)
value
}
pinvGauss <-
function (q, nu, lambda, lower.tail = TRUE, log.p = FALSE)
{
N <- max(length(q), length(nu), length(lambda))
q <- rep(q, length.out = N)
nu <- rep(nu, length.out = N)
lambda <- rep(lambda, length.out = N)
if (lower.tail == TRUE) {
value <- .C(`pinvGaussR`, as.double(q), as.double(nu),
as.double(lambda), as.integer(N), val = double(N),PACKAGE="SuppDists")$val
}
else {
value <- .C(`uinvGaussR`, as.double(q), as.double(nu),
as.double(lambda), as.integer(N), val = double(N),PACKAGE="SuppDists")$val
}
if (log.p == TRUE)
value <- log(value)
value
}
pJohnson <-
function (q, parms, lower.tail = TRUE, log.p = FALSE)
{
tfun <- function(x) if (x == "SN")
1
else if (x == "SL")
2
else if (x == "SU")
3
else 4
vecFromList <- function(item, aList) {
if (!is.list(aList[[1]]))
return(aList[[item]])
else {
tVec <- vector(length = 0)
for (i in 1:length(aList)) {
tVec <- append(tVec, (aList[[i]])[[item]])
}
}
tVec
}
gamma <- vecFromList(1, parms)
delta <- vecFromList(2, parms)
xi <- vecFromList(3, parms)
lambda <- vecFromList(4, parms)
type <- vecFromList(5, parms)
type <- sapply(type, tfun)
N <- max(length(gamma), length(q))
q <- rep(q, length.out = N)
gamma <- rep(gamma, length.out = N)
delta <- rep(delta, length.out = N)
xi <- rep(xi, length.out = N)
lambda <- rep(lambda, length.out = N)
type <- rep(type, length.out = N)
if (lower.tail == TRUE) {
value <- .C(`pJohnsonR`, as.double(q), as.double(gamma),
as.double(delta), as.double(xi), as.double(lambda),
as.integer(type), as.integer(N), val = double(N),PACKAGE="SuppDists")$val
}
else {
value <- .C(`uJohnsonR`, as.double(q), as.double(gamma),
as.double(delta), as.double(xi), as.double(lambda),
as.integer(type), as.integer(N), val = double(N),PACKAGE="SuppDists")$val
}
if (log.p == TRUE)
value <- log(value)
value
}
pKendall <-
function (q, N, lower.tail = TRUE, log.p = FALSE)
{
M <- max(length(q), length(N))
q <- rep(q, length.out = M)
N <- rep(N, length.out = M)
if (lower.tail == TRUE) {
value <- .C(`pKendallR`, as.integer(N), as.double(q),
as.integer(M), val = double(M),PACKAGE="SuppDists")$val
}
else {
value <- .C(`uKendallR`, as.integer(N), as.double(q),
as.integer(M), val = double(M),PACKAGE="SuppDists")$val
}
if (log.p == TRUE)
value <- log(value)
value
}
pKruskalWallis <-
function (q, c, N, U, lower.tail = TRUE, log.p = FALSE)
{
M <- max(length(q), length(c), length(N), length(U))
q <- rep(q, length.out = M)
c <- rep(c, length.out = M)
n <- rep(N, length.out = M)
U <- rep(U, length.out = M)
Ns <- rep(FALSE, length.out = M)
if (lower.tail == TRUE) {
value <- .C(`pKruskalWallisR`, as.double(q), as.integer(c),
as.integer(n), as.double(U), as.integer(Ns), as.integer(M),
val = double(M),PACKAGE="SuppDists")$val
}
else {
value <- .C(`uKruskalWallisR`, as.double(q), as.integer(c),
as.integer(n), as.double(U), as.integer(Ns), as.integer(M),
val = double(M),PACKAGE="SuppDists")$val
}
if (log.p == TRUE)
value <- log(value)
value
}
pmaxFratio <-
function (q, df, k, lower.tail = TRUE, log.p = FALSE)
{
N <- max(length(q), length(df), length(k))
q <- rep(q, length.out = N)
df <- rep(df, length.out = N)
k <- rep(k, length.out = N)
if (lower.tail == TRUE) {
value <- .C(`pmaxFratioR`, as.double(q), as.integer(df),
as.integer(k), as.integer(N), val = double(N),PACKAGE="SuppDists")$val
}
else {
value <- .C(`umaxFratioR`, as.double(q), as.integer(df),
as.integer(k), as.integer(N), val = double(N),PACKAGE="SuppDists")$val
}
if (log.p == TRUE)
value <- log(value)
value
}
pNormScore <-
function (q, c, N, U, lower.tail = TRUE, log.p = FALSE)
{
M <- max(length(q), length(c), length(N), length(U))
q <- rep(q, length.out = M)
c <- rep(c, length.out = M)
n <- rep(N, length.out = M)
U <- rep(U, length.out = M)
Ns <- rep(TRUE, length.out = M)
if (lower.tail == TRUE) {
value <- .C(`pKruskalWallisR`, as.double(q), as.integer(c),
as.integer(n), as.double(U), as.integer(Ns), as.integer(M),
val = double(M),PACKAGE="SuppDists")$val
}
else {
value <- .C(`uKruskalWallisR`, as.double(q), as.integer(c),
as.integer(n), as.double(U), as.integer(Ns), as.integer(M),
val = double(M),PACKAGE="SuppDists")$val
}
if (log.p == TRUE)
value <- log(value)
value
}
pPearson <-
function (q, N, rho = 0, lower.tail = TRUE, log.p = FALSE)
{
M <- max(length(q), length(rho), length(N))
q <- rep(q, length.out = M)
rho <- rep(rho, length.out = M)
N <- rep(N, length.out = M)
if (lower.tail == TRUE) {
value <- .C(`pcorrR`, as.double(q), as.double(rho), as.integer(N),
as.integer(M), val = double(M),PACKAGE="SuppDists")$val
}
else {
value <- .C(`ucorrR`, as.double(q), as.double(rho), as.integer(N),
as.integer(M), val = double(M),PACKAGE="SuppDists")$val
}
if (log.p == TRUE)
value <- log(value)
value
}
pSpearman <-
function (q, r, lower.tail = TRUE, log.p = FALSE)
{
M <- max(length(q), length(r))
q <- rep(q, length.out = M)
r <- rep(r, length.out = M)
N <- rep(2, length.out = M)
rho <- rep(TRUE, length.out = M)
if (lower.tail == TRUE) {
value <- .C(`pFriedmanR`, as.double(q), as.integer(r),
as.integer(N), as.integer(M), as.integer(rho), val = double(M),PACKAGE="SuppDists")$val
}
else {
value <- .C(`uFriedmanR`, as.double(q), as.integer(r),
as.integer(N), as.integer(M), as.integer(rho), val = double(M),PACKAGE="SuppDists")$val
}
if (log.p == TRUE)
value <- log(value)
value
}
qFriedman <-
function (p, r, N, lower.tail = TRUE, log.p = FALSE)
{
if (log.p == TRUE)
p <- exp(p)
if (lower.tail == FALSE)
p <- 1 - p
M <- max(length(p), length(r), length(N))
p <- rep(p, length.out = M)
r <- rep(r, length.out = M)
N <- rep(N, length.out = M)
rho <- rep(FALSE, length.out = M)
.C(`qFriedmanR`, as.double(p), as.integer(r), as.integer(N),
as.integer(M), as.integer(rho), val = double(M),PACKAGE="SuppDists")$val
}
qghyper <-
function (p, a, k, N, lower.tail = TRUE, log.p = FALSE)
{
if (log.p == TRUE)
p <- exp(p)
if (lower.tail == FALSE)
p <- 1 - p
M <- max(length(p), length(a), length(k), length(N))
p <- rep(p, length.out = M)
a <- rep(a, length.out = M)
k <- rep(k, length.out = M)
N <- rep(N, length.out = M)
value <- .C(`qghyperR`, as.double(p), as.double(a), as.double(k),
as.double(N), as.integer(M), val = double(M),PACKAGE="SuppDists")$val
value
}
qinvGauss <-
function (p, nu, lambda, lower.tail = TRUE, log.p = FALSE)
{
if (log.p == TRUE)
p <- exp(p)
if (lower.tail == FALSE)
p <- 1 - p
N <- max(length(p), length(nu), length(lambda))
p <- rep(p, length.out = N)
nu <- rep(nu, length.out = N)
lambda <- rep(lambda, length.out = N)
.C(`qinvGaussR`, as.double(p), as.double(nu), as.double(lambda),
as.integer(N), value = double(N),PACKAGE="SuppDists")$value
}
qJohnson <-
function (p, parms, lower.tail = TRUE, log.p = FALSE)
{
tfun <- function(x) if (x == "SN")
1
else if (x == "SL")
2
else if (x == "SU")
3
else 4
if (log.p == TRUE)
p <- exp(p)
if (lower.tail == FALSE)
p <- 1 - p
vecFromList <- function(item, aList) {
if (!is.list(aList[[1]]))
return(aList[[item]])
else {
tVec <- vector(length = 0)
for (i in 1:length(aList)) {
tVec <- append(tVec, (aList[[i]])[[item]])
}
}
tVec
}
gamma <- vecFromList(1, parms)
delta <- vecFromList(2, parms)
xi <- vecFromList(3, parms)
lambda <- vecFromList(4, parms)
type <- vecFromList(5, parms)
type <- sapply(type, tfun)
N <- max(length(gamma), length(p))
p <- rep(p, length.out = N)
gamma <- rep(gamma, length.out = N)
delta <- rep(delta, length.out = N)
xi <- rep(xi, length.out = N)
lambda <- rep(lambda, length.out = N)
type <- rep(type, length.out = N)
.C(`qJohnsonR`, as.double(p), as.double(gamma), as.double(delta),
as.double(xi), as.double(lambda), as.integer(type), as.integer(N),
val = double(N),PACKAGE="SuppDists")$val
}
qKendall <-
function (p, N, lower.tail = TRUE, log.p = FALSE)
{
if (log.p == TRUE)
p <- exp(p)
if (lower.tail == FALSE)
p <- 1 - p
M <- max(length(p), length(N))
p <- rep(p, length.out = M)
N <- rep(N, length.out = M)
.C(`qKendallR`, as.integer(N), as.double(p), as.integer(M),
val = double(M),PACKAGE="SuppDists")$val
}
qKruskalWallis <-
function (p, c, N, U, lower.tail = TRUE, log.p = FALSE)
{
if (log.p == TRUE)
p <- exp(p)
if (lower.tail == FALSE)
p <- 1 - p
M <- max(length(p), length(c), length(N), length(U))
p <- rep(p, length.out = M)
c <- rep(c, length.out = M)
N <- rep(N, length.out = M)
U <- rep(U, length.out = M)
Ns <- rep(FALSE, length.out = M)
.C(`qKruskalWallisR`, as.double(p), as.integer(c), as.integer(N),
as.double(U), as.integer(Ns), as.integer(M), val = double(M),PACKAGE="SuppDists")$val
}
qmaxFratio <-
function (p, df, k, lower.tail = TRUE, log.p = FALSE)
{
if (lower.tail == FALSE)
p <- 1 - p
if (log.p == TRUE)
p <- exp(p)
N <- max(length(p), length(df), length(k))
p <- rep(p, length.out = N)
df <- rep(df, length.out = N)
k <- rep(k, length.out = N)
.C(`qmaxFratioR`, as.double(p), as.integer(df), as.integer(k),
as.integer(N), val = double(N),PACKAGE="SuppDists")$val
}
qNormScore <-
function (p, c, N, U, lower.tail = TRUE, log.p = FALSE)
{
if (log.p == TRUE)
p <- exp(p)
if (lower.tail == FALSE)
p <- 1 - p
M <- max(length(p), length(c), length(N), length(U))
p <- rep(p, length.out = M)
c <- rep(c, length.out = M)
N <- rep(N, length.out = M)
U <- rep(U, length.out = M)
Ns <- rep(TRUE, length.out = M)
.C(`qKruskalWallisR`, as.double(p), as.integer(c), as.integer(N),
as.double(U), as.integer(Ns), as.integer(M), val = double(M),PACKAGE="SuppDists")$val
}
qPearson <-
function (p, N, rho = 0, lower.tail = TRUE, log.p = FALSE)
{
if (log.p == TRUE)
p <- exp(p)
if (lower.tail == FALSE)
p <- 1 - p
M <- max(length(p), length(rho), length(N))
p <- rep(p, length.out = M)
rho <- rep(rho, length.out = M)
N <- rep(N, length.out = M)
.C(`qcorrR`, as.double(p), as.double(rho), as.integer(N),
as.integer(M), val = double(M),PACKAGE="SuppDists")$val
}
qSpearman <-
function (p, r, lower.tail = TRUE, log.p = FALSE)
{
if (log.p == TRUE)
p <- exp(p)
if (lower.tail == FALSE)
p <- 1 - p
M <- max(length(p), length(r))
p <- rep(p, length.out = M)
r <- rep(r, length.out = M)
N <- rep(2, length.out = M)
rho <- rep(TRUE, length.out = M)
.C(`qFriedmanR`, as.double(p), as.integer(r), as.integer(N),
as.integer(M), as.integer(rho), val = double(M),PACKAGE="SuppDists")$val
}
rFriedman <-
function (n, r, N)
{
n <- if (length(n) > 1)
length(n)
else n
M <- max(length(r), length(N))
r <- rep(r, length.out = M)
N <- rep(N, length.out = M)
rho <- rep(FALSE, length.out = M)
.C(`rFriedmanR`, as.integer(r), as.integer(N), as.integer(rho),
as.integer(n), as.integer(M), value = double(n),PACKAGE="SuppDists")$value
}
rghyper <-
function (n, a, k, N)
{
n <- if (length(n) > 1)
length(n)
else n
K <- max(length(a), length(k), length(N))
a <- rep(a, length.out = K)
k <- rep(k, length.out = K)
N <- rep(N, length.out = K)
.C(`rghyperR`, as.double(a), as.double(k), as.double(N),
as.integer(n), as.integer(K), value = double(n),PACKAGE="SuppDists")$value
}
rinvGauss <-
function (n, nu, lambda)
{
n <- if (length(n) > 1)
length(n)
else n
N <- max(length(nu), length(lambda))
nu <- rep(nu, length.out = N)
lambda <- rep(lambda, length.out = N)
.C(`rinvGaussR`, as.double(nu), as.double(lambda), as.integer(n),
as.integer(N), value = double(n),PACKAGE="SuppDists")$value
}
rJohnson <-
function (n, parms)
{
tfun <- function(x) if (x == "SN")
1
else if (x == "SL")
2
else if (x == "SU")
3
else 4
vecFromList <- function(item, aList) {
if (!is.list(aList[[1]]))
return(aList[[item]])
else {
tVec <- vector(length = 0)
for (i in 1:length(aList)) {
tVec <- append(tVec, (aList[[i]])[[item]])
}
}
tVec
}
n <- if (length(n) > 1)
length(n)
else n
gamma <- vecFromList(1, parms)
delta <- vecFromList(2, parms)
xi <- vecFromList(3, parms)
lambda <- vecFromList(4, parms)
type <- vecFromList(5, parms)
type <- sapply(type, tfun)
M <- length(gamma)
.C(`rJohnsonR`, as.double(gamma), as.double(delta), as.double(xi),
as.double(lambda), as.integer(type), as.integer(n), as.integer(M),
val = double(n),PACKAGE="SuppDists")$val
}
rKendall <-
function (n, N)
{
n <- if (length(n) > 1)
length(n)
else n
M <- length(N)
.C(`rKendallR`, as.integer(N), as.integer(n), as.integer(M),
val = double(n),PACKAGE="SuppDists")$val
}
rKruskalWallis <-
function (n, c, N, U)
{
n <- if (length(n) > 1)
length(n)
else n
M <- max(length(c), length(N), length(U))
c <- rep(c, length.out = M)
N <- rep(N, length.out = M)
U <- rep(U, length.out = M)
Ns <- rep(FALSE, length.out = M)
.C(`rKruskalWallisR`, randArray = double(n), as.integer(n),
as.integer(M), as.integer(c), as.integer(N), as.double(U),
as.integer(Ns),PACKAGE="SuppDists" )$randArray
}
rmaxFratio <-
function (n, df, k)
{
n <- if (length(n) > 1)
length(n)
else n
M <- max(length(df), length(k))
df <- rep(df, length.out = M)
k <- rep(k, length.out = M)
.C(`rmaxFratioR`, as.integer(df), as.integer(k), as.integer(n),
as.integer(M), value = double(n),PACKAGE="SuppDists")$value
}
## .Defunct
## no alternative
#rMWC1019 <-
#function (n, new.start = FALSE, seed = 556677)
#{
# n <- if (length(n) == 1)
# n
# else length(n)
# .C(`MWC1019R`, val = double(n), as.integer(n), as.integer(new.start),
# as.integer(seed),PACKAGE="SuppDists")$val
#}
rNormScore <-
function (n, c, N, U)
{
n <- if (length(n) > 1)
length(n)
else n
M <- max(length(c), length(N), length(U))
c <- rep(c, length.out = M)
N <- rep(N, length.out = M)
U <- rep(U, length.out = M)
Ns <- rep(TRUE, length.out = M)
.C(`rKruskalWallisR`, randArray = double(n), as.integer(n),
as.integer(M), as.integer(c), as.integer(N), as.double(U),
as.integer(Ns),PACKAGE="SuppDists" )$randArray
}
rPearson <-
function (n, N, rho = 0)
{
n <- if (length(n) > 1)
length(n)
else n
M <- max(length(rho), length(N))
rho <- rep(rho, length.out = M)
N <- rep(N, length.out = M)
.C(`rcorrR`, as.double(rho), as.integer(N), as.integer(n),
as.integer(M), val = double(n),PACKAGE="SuppDists")$val
}
rSpearman <-
function (n, r)
{
n <- if (length(n) > 1)
length(n)
else n
M <- length(r)
r <- rep(r, length.out = M)
N <- rep(2, length.out = M)
rho <- rep(TRUE, length.out = M)
.C(`rFriedmanR`, as.integer(r), as.integer(N), as.integer(rho),
as.integer(n), as.integer(M), value = double(n),PACKAGE="SuppDists")$value
}
## use .Defunct function?
## see ~/src/R/R-3.5.1/src/library/base/man/base-defunct.Rd
## suggest package RcppZiggurat instead
#rziggurat <-
#function (n, normal = TRUE, new.start = FALSE, seed = 556677)
#{
# n <- if (length(n) > 1)
# length(n)
# else n
# .C(`ziggR`, val = double(n), as.integer(n), as.integer(normal),
# as.integer(new.start), as.integer(seed),PACKAGE="SuppDists")$val
#}
sFriedman <-
function (r, N)
{
M <- max(length(r), length(N))
r <- rep(r, length.out = M)
N <- rep(N, length.out = M)
rho <- rep(FALSE, length.out = M)
value <- .C(`sFriedmanR`, as.integer(r), as.integer(N), as.integer(rho),
as.integer(M), mn = double(M), med = double(M), mod = double(M),
var = double(M), third = double(M), fourth = double(M),PACKAGE="SuppDists")
aList <- list(title = "Friedman's chi-square", r = r, N = N)
makeStatList(aList, value$mn, value$med, value$var, value$mod,
value$third, value$fourth, -1)
}
sghyper <-
function (a, k, N)
{
M <- max(length(a), length(k), length(N))
a <- rep(a, length.out = M)
k <- rep(k, length.out = M)
N <- rep(N, length.out = M)
value <- .C(`sghyperR`, as.double(a), as.double(k), as.double(N),
as.integer(M), mn = double(M), med = double(M), mod = double(M),
var = double(M), third = double(M), fourth = double(M),PACKAGE="SuppDists")
aList <- list(title = "Generalized Hypergeometric", a = a,
k = k, N = N)
makeStatList(aList, value$mn, value$med, value$var, value$mod,
value$third, value$fourth, -1)
}
sinvGauss <-
function (nu, lambda)
{
N <- max(length(nu), length(lambda))
nu <- rep(nu, length.out = N)
lambda <- rep(lambda, length.out = N)
med <- qinvGauss(0.5, nu, lambda)
nu[nu<=0]<-NA
lambda[lambda<=0]<-NA
factor <- (nu^2)/lambda
var <- nu * factor
k3 <- 3 * var * factor
k4 <- 5 * k3 * factor
mod <- -1.5 * factor + nu * sqrt(1 + 2.25 * (nu/lambda)^2)
third <- k3
fourth <- k4 + 3 * var^2
aList <- list(title = "Inverse Gaussian", nu = nu, lambda = lambda)
makeStatList(aList, nu, med, var, mod, third, fourth, -1)
}
sJohnson <-
function (parms)
{
tfun <- function(x) if (x == "SN")
1
else if (x == "SL")
2
else if (x == "SU")
3
else 4
vecFromList <- function(item, aList) {
if (!is.list(aList[[1]]))
return(aList[[item]])
else {
tVec <- vector(length = 0)
for (i in 1:length(aList)) {
tVec <- append(tVec, (aList[[i]])[[item]])
}
}
tVec
}
gamma <- vecFromList(1, parms)
delta <- vecFromList(2, parms)
xi <- vecFromList(3, parms)
lambda <- vecFromList(4, parms)
type <- vecFromList(5, parms)
type <- sapply(type, tfun)
N <- length(gamma)
value <- .C(`sJohnsonR`, as.double(gamma), as.double(delta),
as.double(xi), as.double(lambda), as.integer(type), as.integer(N),
mn = double(N), med = double(N), mod = double(N), var = double(N),
third = double(N), fourth = double(N),PACKAGE="SuppDists")
aList <- list(title = "Johnson Distribution", gamma = gamma,
delta = delta, xi = xi, lambda = lambda, type = type)
makeStatList(aList, value$mn, value$med, value$var, value$mod,
value$third, value$fourth, -1)
}
sKendall <-
function (N)
{
M <- length(N)
mn <- rep(0, length.out = M)
med <- rep(0, length.out = M)
mod <- rep(0, length.out = M)
third <- rep(0, length.out = M)
var <- (4 * N + 10)/(9 * N * (N - 1))
fourth <- .C(`fourthKendallR`, as.integer(N), as.integer(M),
val = double(M),PACKAGE="SuppDists")$val
aList <- list(title = "Kendall's Tau", N = N)
makeStatList(aList, mn, med, var, mod, third, fourth, -1)
}
sKruskalWallis <-
function (c, N, U)
{
M <- max(length(c), length(N), length(U))
c <- rep(c, length.out = M)
n <- rep(N, length.out = M)
U <- rep(U, length.out = M)
Ns <- rep(FALSE, length.out = M)
value <- .C(`sKruskalWallisR`, as.integer(c), as.integer(n),
as.double(U), as.integer(Ns), as.integer(M), var = double(M),
mod = double(M), third = double(M), fourth = double(M),PACKAGE="SuppDists")
mn <- (c - 1)
aList <- list(title = "Kruskal Wallis", c = c, N = n, U = U)
median <- qKruskalWallis(0.5, c, n, U, Ns)
makeStatList(aList, mn, median, value$var, value$mod, value$third,
value$fourth, -1)
}
smaxFratio <-
function (df, k)
{
N <- max(length(df), length(k))
df <- rep(df, length.out = N)
k <- rep(k, length.out = N)
value <- .C(`smaxFratioR`, as.integer(df), as.integer(k),
as.integer(N), mn = double(N), med = double(N), mod = double(N),
var = double(N), third = double(N), fourth = double(N),PACKAGE="SuppDists")
aList <- list(title = "Maximum F ratio", df = df, k = k)
makeStatList(aList, value$mn, value$med, value$var, value$mod,
value$third, value$fourth, 2)
}
sNormScore <-
function (c, N, U)
{
M <- max(length(c), length(N), length(U))
c <- rep(c, length.out = M)
n <- rep(N, length.out = M)
U <- rep(U, length.out = M)
Ns <- rep(TRUE, length.out = M)
value <- .C(`sKruskalWallisR`, as.integer(c), as.integer(n),
as.double(U), as.integer(Ns), as.integer(M), var = double(M),
mod = double(M), third = double(M), fourth = double(M),PACKAGE="SuppDists")
mn <- (c - 1)
aList <- list(title = "Normal Scores", c = c, N = n, U = U)
median <- qNormScore(0.5, c, n, U)
makeStatList(aList, mn, median, value$var, value$mod, value$third,
value$fourth, -1)
}
sPearson <-
function (N, rho = 0)
{
M <- max(length(rho), length(N))
rho <- rep(rho, length.out = M)
N <- rep(N, length.out = M)
value <- .C(`scorrR`, as.double(rho), as.integer(N), as.integer(M),
mn = double(M), med = double(M), mod = double(M), var = double(M),
third = double(M), fourth = double(M),PACKAGE="SuppDists")
aList <- list(title = "Correlation coefficient", rho = rho,
N = N)
makeStatList(aList, value$mn, value$med, value$var, value$mod,
value$third, value$fourth, -1)
}
sSpearman <-
function (r)
{
M <- length(r)
r <- rep(r, length.out = M)
N <- rep(2, length.out = M)
rho <- rep(TRUE, length.out = M)
value <- .C(`sFriedmanR`, as.integer(r), as.integer(N), as.integer(rho),
as.integer(M), mn = double(M), med = double(M), mod = double(M),
var = double(M), third = double(M), fourth = double(M),PACKAGE="SuppDists")
aList <- list(title = "Spearman's rho", r = r)
makeStatList(aList, value$mn, value$med, value$var, value$mod,
value$third, value$fourth, -1)
}
tghyper <-
function (a, k, N)
{
value <- .C(`tghyperR`, as.double(a), as.double(k), as.double(N),
strn =paste(rep(" ", 128), collapse=""),PACKAGE="SuppDists" )
value$strn
}
|
fe0a3dd26137764d23b2b711a27bd1082420e87d | c5a3060f7b0d69ee796b3de261101b800462b79e | /cachematrix.R | 143a6416eb76fe7d03dc1313b9386faf88fd4f3c | [] | no_license | Offikial/ProgrammingAssignment2 | df10e08432a913614393f3f6028fdff614695db2 | aefc80985e496a66c0502cf77efd5810b9ba1de6 | refs/heads/master | 2021-01-18T06:36:19.116107 | 2014-07-23T08:25:54 | 2014-07-23T08:25:54 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 2,326 | r | cachematrix.R | ## Below are two functions that are used to create a special object that stores
## an inversible matrix and cache's its inverse.
# The first function, makeCacheMatrix creates a special "matrix", which is really a
# list containing a function to:
## -- set the value of the matrix, x
## -- get the value of the matrix, x
## -- set the value of the inverse matrix, m
## -- get the value of the inverse matrix, m
# The second function calculates the inverse of the special matrix (x) as needed
# - First, it checks to see if the inverse has already been calculated.
# If so, it gets the inverse (m) from the cache and skips the computation.
# - Otherwise, it calculates the inverse of the data and sets the value
# of the inverse (m) in the cache.
## This function creates a special "matrix" object that can be cache data
makeCacheMatrix <- function(x = matrix()) {
m <- NULL
#Function that stores matrix x in cache
set <- function(y) {
x <<- y
m <<- NULL
}
#Function that returns matrix x to new scope
get <- function() x
#Function that stores calculated value (m) in cache
setvalue <- function(solve) {
m <<- solve
}
#Function that returns calculated value (m) to new scope
getvalue <- function() m
#Make functions available in new scope
list(set = set,
get = get,
setvalue = setvalue,
getvalue = getvalue)
}
## This function computes the inverse of the special "matrix"
cacheSolve <- function(x, ...) {
#Check for the inverse (m)
m <- x$getvalue()
#If inverse is in cache, return inverse (m)
if(!is.null(m)) {
message("getting cached data")
return(m)
}
#Otherwise, get the inverse(m) of the data (x)
data <- x$get()
m <- solve(data, ...)
#Store inverse(m) in cache, for later use
x$setvalue(m)
## Return a matrix that is the inverse of 'x'
m
}
### SAMPLE PROGRAM ###
#Inversible Matrix
mymatrix <- rbind(c(1, -2), c(-2, 1))
#Special Matrix
special <- makeCacheMatrix(mymatrix)
#Calculate Inverse of Special Matrix
result1 <- cacheSolve(special)
#Get Inverse of Special Matrix from Cache
result2 <- cacheSolve(special)
|
73e1cda48bd3f2d70ad6f99147bac0327810a8d5 | 84f7a8fb119455b18bd59db8238b8f663bf9fd33 | /Correlations.R | 12a1b3b1dc35673679712faa338afc9625dbfa12 | [] | no_license | LiamCullenCS/ELO-Ratings | d45939d221bc9e6236e84e05734e6d2f0d8c3416 | f739ae2ac30e457c7253516eb9d44ced480c9d98 | refs/heads/master | 2020-05-01T01:20:35.571723 | 2019-04-06T18:26:41 | 2019-04-06T18:26:41 | 177,193,162 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 484 | r | Correlations.R | library(nflscrapR)
library(tidyverse)
library(ggplot2)
TeamDistributions <- read.csv(file = "TeamDistributions.csv", header = TRUE, sep = ",")
rankings <- read.csv(file = "ELO Rankings.csv", header = TRUE, sep = ",")
View(TeamDistributions)
TeamDist <- as_tibble(TeamDistributions)
Sacks <- TeamDist %>% pull(SackPCT)
Pass <- TeamDist %>% pull(PassPCT)
Run <- TeamDist %>% pull(RunPCT)
ratings <- rankings %>% pull(rating)
cor(Sacks, ratings)
cor(Pass, ratings)
cor(Run, ratings) |
d2e78f24bb9079f1204e275eed47d4316acd80e7 | b383bc7cc80209c5c7d2d56f8902448eee384b5e | /man/cluster.evaluation.Rd | 4db06c55d0e6289cba9ce99ffa66c39e18f9c77e | [] | no_license | cran/TSclust | 73fa98f494cc373d9bc7bda11d3fa661afb687de | 2231e2b398f816965d67039208617f4e9d731fc1 | refs/heads/master | 2021-07-11T21:43:47.095710 | 2020-07-22T20:10:21 | 2020-07-22T20:10:21 | 17,693,906 | 11 | 7 | null | null | null | null | UTF-8 | R | false | false | 3,011 | rd | cluster.evaluation.Rd | \name{cluster.evaluation}
\alias{cluster.evaluation}
%- Also NEED an '\alias' for EACH other topic documented here.
\title{
Clustering Evaluation Index Based on Known Ground Truth%% ~~function to do ... ~~
}
\description{
Computes the similarity between the true cluster solution and the one obtained with a method under evaluation.
%% ~~ A concise (1-5 lines) description of what the function does. ~~
}
\usage{
cluster.evaluation(G, S)
}
%- maybe also 'usage' for other objects documented here.
\arguments{
\item{G}{
Integer vector with the labels of the true cluster solution. Each element of the vector specifies the cluster 'id' that the element belongs to.
%% ~~Describe \code{x} here~~
}
\item{S}{
Integer vector with the labels of the cluster solution to be evaluated. Each element of the vector specifies the cluster 'id' that the element belongs to.
%% ~~Describe \code{y} here~~
}
}
\details{
The measure of clustering evaluation is defined as \deqn{ Sim(G,C) = 1/k \sum_{i=1}^k \max_{1\leq j\leq k} Sim(G_i,C_j), } where \deqn{Sim(G_i, C_j) = \frac{ 2 | G_i \cap C_j|}{ |G_i| + |C_j|}}
with |.| denoting the cardinality of the elements in the set. This measure has been used for comparing different clusterings, e.g. in Kalpakis et al. (2001) and Pértega and Vilar (2010).
}
\value{
The computed index.
%% ~Describe the value returned
%% If it is a LIST, use
%% \item{comp1 }{Description of 'comp1'}
%% \item{comp2 }{Description of 'comp2'}
%% ...
}
\references{
Larsen, B. and Aone, C. (1999) Fast and effective text mining using linear-time document clustering. \emph{Proc. KDD' 99}.16--22. \cr
Kalpakis, K., Gada D. and Puttagunta, V. (2001) Distance measures for effective clustering of arima time-series. \emph{Proceedings 2001 IEEE International Conference on Data Mining}, 273--280. \cr
Pértega S. and Vilar, J.A (2010) Comparing several parametric and nonparametric approaches to time series clustering: A simulation study. \emph{J. Classification}, \bold{27(3)}, 333-362.
Montero, P and Vilar, J.A. (2014) \emph{TSclust: An R Package for Time Series Clustering.} Journal of Statistical Software, 62(1), 1-43. \url{http://www.jstatsoft.org/v62/i01/.}
}
\author{
Pablo Montero Manso, José Antonio Vilar.
%% ~~who you are~~
}
\note{
This index is not simmetric.
}
%% ~Make other sections like Warning with \section{Warning }{....} ~
\seealso{
\code{\link[fpc]{cluster.stats}}, \code{\link[clValid]{clValid}}, \code{\link[clv]{std.ext}}
}
\examples{
#create a true cluster
#(first 4 elements belong to cluster '1', next 4 to cluster '2' and the last 4 to cluster '3'.
true_cluster <- c(1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3)
#the cluster to be tested
new_cluster <- c( 2, 1, 2, 3, 3, 2, 2, 1, 3, 3, 3, 3)
#get the index
cluster.evaluation(true_cluster, new_cluster)
#it can be seen that the index is not simmetric
cluster.evaluation(new_cluster, true_cluster)
}
|
38a4fc1d3bdd354f7e15da331ffcf6fd54ac6130 | cde8ee6cf40b7f8856ac1bb2ad3760eb8627694e | /scripts/sv1.R | 3db646146914007fe5f366d15a789b4f5fd429cd | [] | no_license | pourzanj/homebuying | f6009196637bab8f0ae346eade6f8f0d923f3ab6 | 08bbf1a21cfad02b3be0365a4f8553f2f7d64518 | refs/heads/master | 2023-02-08T10:36:34.021505 | 2023-01-20T22:44:57 | 2023-01-20T22:44:57 | 234,444,364 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 16,602 | r | sv1.R | library(tidyverse)
library(tibbletime)
library(tidyquant)
library(cmdstanr)
library(posterior)
library(bayesplot)
library(moments)
spx <-
tq_get(c("^GSPC"),
get = "stock.prices",
from = "2002-01-01",
to = "2022-12-31") %>%
mutate(y = 100*log(close/lag(close))) %>%
na.omit() %>%
mutate(week = isoweek(date)) %>%
mutate(year = if_else(month(date) == 12 & week == 1, year(date)+1, year(date))) %>%
mutate(day = wday(date, label = TRUE))
vix <-
tq_get(c("^VIX"),
get = "stock.prices",
from = "2002-01-01",
to = "2022-12-31") %>%
select(date, vix = close)
#############
# Initialization fit
#############
model <- cmdstan_model("stan/sv1.stan")
model <- cmdstan_model("stan/sv13.stan")
model <- cmdstan_model("stan/sv18.stan")
init <-
replicate(4, list(mu_ret = 0.1,
phi_raw = c(0.99, 0.9), sigma = c(0.1,0.3),
v1 = rep(0.0, nrow(spx)),
v2 = rep(0.0, nrow(spx))), simplify = FALSE)
fit <-
model$sample(
data = list(T = nrow(spx), y = spx$y,
M = 2, y_ahead = c(0, 0)),
seed = 1994,
iter_warmup = 5e2,
iter_sampling = 5e2,
chains = 4,
parallel_chains = 4,
refresh = 10,
max_treedepth = 10,
adapt_delta = 0.8,
init = init
)
fit$summary(c("lp__", "mu_ret", "mu", "phi", "sigma"))
#############
# Fit full model using initialization
#############
# model <- cmdstan_model("stan/sv11.stan")
#
# # Set intial values
# pars0 <-
# fit$draws(c("mu_ret", "rho", "mu", "phi", "sigma")) %>%
# as_draws_df() %>%
# as_tibble() %>%
# filter(.draw == 1821)
#
# v0 <- as.vector(fit$draws(c("v"), format = "draws_matrix")[1821,])
#
# init <-
# replicate(4, list(mu_ret = pars0$mu_ret,
# mu = pars0$mu, phi = pars0$phi, sigma = pars0$sigma,
# rho = pars0$rho,
# b = c(0, 0, 0),
# v = v0), simplify = FALSE)
#
# saveRDS(init, "init.RDS")
# init <- readRDS(init, "init.RDS")
#
# # Set inverse metric
# inv_metric_orig <- diag(fit$inv_metric()[[1]])
# inv_metric_new <- c(inv_metric_orig, rep(0.2^2, 3))
#
# saveRDS(inv_metric_new, "inv_metric.RDS")
# inv_metric_new <- readRDS("inv_metric.RDS")
#
#
# # Fit
# fit <-
# model$sample(
# data = list(T = nrow(spx), y = spx$y, K = 3, knots = c(-1.0, -0.5, 0)),
# seed = 1994,
# iter_warmup = 0e3,
# iter_sampling = 1e3,
# chains = 4,
# parallel_chains = 4,
# refresh = 20,
# max_treedepth = 6,
# adapt_delta = 0.8,
# metric = "diag_e",
# inv_metric = inv_metric_new,
# adapt_engaged = FALSE,
# step_size = 0.02,
# init = init
# )
#############
# Analyze
#############
fit$summary(c("sum_log_lik", "sum_log_lik_ahead"))
fit$summary(c("lp__", "mu_ret", "mu", "sigma", "phi", "l", "p", "gamma"))
s <- fit$summary("s") %>% bind_cols(spx)
s %>% ggplot(aes(date, median)) + geom_line() + geom_ribbon(aes(ymin = q5, ymax = q95), alpha = 0.2) + scale_y_log10()
h <- fit$summary("h") %>% bind_cols(spx)
h %>% ggplot(aes(date, median)) + geom_line() + geom_ribbon(aes(ymin = q5, ymax = q95), alpha = 0.2)
v <- fit$summary("v") %>% bind_cols(spx)
v %>% filter(year(date) == 2022) %>% ggplot(aes(date, median)) + geom_pointrange(aes(ymin = q5, ymax = q95))
fit$draws(c("mu_ret", "rho", "mu", "phi", "sigma", "sum_log_lik", "sum_log_lik_ahead")) %>% mcmc_pairs()
y_rep <- fit$summary("y_rep") %>% bind_cols(spx)
y_rep_draws <- fit$draws("y_rep") %>% as_draws_matrix()
p <- map_dbl(1:nrow(spx), function(i) mean(spx$y[i] >= y_rep_draws[,i]))
# Redraw new y_rep
temp <-
fit$draws(c("mu_ret", "rho", "mu", "phi", "sigma", "alpha", "beta", "h")) %>%
as_draws_df() %>%
as_tibble() %>%
select(-.chain, -.iteration) %>%
sample_n(1) %>%
pivot_longer(c(-.draw,-mu_ret, -rho, -mu, -phi, -sigma, -alpha, -beta)) %>%
mutate(date = spx$date, y = spx$y, s = s$median)
temp %>%
rename(h = value) %>%
# mutate(mul = exp(0.4*lag(h)+-0.3*lag(h)^2)) %>%
mutate(mul = exp(alpha*lag(h)+beta*pmax(-0.7, lag(h)))) %>%
mutate(v_rep = rnorm(nrow(.))) %>%
mutate(v_rep1 = mul*rnorm(nrow(.))) %>%
mutate(h_rep = phi*lag(h) + sigma*v_rep) %>%
mutate(h_rep1 = phi*lag(h) + sigma*v_rep1) %>%
mutate(s_rep = exp((mu+h_rep)/2)) %>%
mutate(s_rep1 = exp((mu+h_rep1)/2)) %>%
mutate(eps = rnorm(nrow(.))) %>%
mutate(y0 = mu_ret + rho*v_rep*s_rep + sqrt(1-rho^2)*s_rep*eps) %>%
mutate(y1 = mu_ret + rho*v_rep1*s_rep1 + sqrt(1-rho^2)*s_rep1*eps) %>%
select(date, s, y, y0, y1) %>%
mutate(sbin = lag(cut(s, quantile(s, c(0, 0.25, 0.5, 0.75, 1))))) %>%
na.omit() %>%
pivot_longer(c(-date, -s, -sbin)) %>%
ggplot(aes(value, color = name)) +
geom_density() +
facet_wrap(sbin ~ ., scales = "free")
s %>%
select(date, s = median, y) %>%
mutate(sbin = lag(cut(s, quantile(s, seq(0, 1, by = 0.25), na.rm = TRUE)))) %>%
mutate(y1 = as.vector(y_rep_draws[sample(1:dim(y_rep_draws)[1], 1),])) %>%
# mutate(y2 = as.vector(y_rep_draws[sample(1:dim(y_rep_draws)[1], 1),])) %>%
# mutate(y3 = as.vector(y_rep_draws[sample(1:dim(y_rep_draws)[1], 1),])) %>%
filter(row_number() > 1) %>%
na.omit() %>%
# mutate(y0 = temp$y0) %>%
# filter(year(date) == 2022) %>%
pivot_longer(c(y, y1)) %>%
ggplot(aes(value, color = name)) +
geom_density() +
# geom_histogram(binwidth = 0.25) +
facet_wrap(sbin ~ ., scales = "free") +
scale_y_sqrt()
s %>%
select(date, s = median, y) %>%
mutate(sbin = lag(cut(s, quantile(s, seq(0, 1, by = 0.25), na.rm = TRUE)))) %>%
mutate(p = p) %>%
filter(row_number() > 1) %>%
na.omit() %>%
ggplot(aes(p)) +
geom_histogram(breaks = seq(0, 1, by = 0.1)) +
facet_wrap(sbin ~ .)
# Compare draws of h and h_rep
hh_rep <-
fit$draws(c("h", "h_rep")) %>%
as_draws_df() %>%
as_tibble() %>%
# sample_n(4) %>%
select(-.chain, -.iteration) %>%
pivot_longer(-.draw) %>%
mutate(i = parse_number(name)) %>%
mutate(name = str_extract(name, "[a-z_]+")) %>%
inner_join(transmute(spx, date, i = row_number()))
hh_rep %>%
ggplot(aes(date, value, color = name)) +
geom_line() +
facet_grid(.draw ~ name)
hh_rep %>%
ggplot(aes(value, color = name)) +
geom_density() +
# geom_histogram() +
# facet_grid(name ~ .draw) +
facet_grid(.draw ~ .)
hh_rep %>%
group_by(name, .draw) %>%
pivot_wider(names_from = name, values_from = value) %>%
summarize(m1_true = moment(h, order = 1, central = FALSE),
m2_true = moment(h, order = 2, central = TRUE),
m3_true = moment(h, order = 3, central = TRUE),
m4_true = moment(h, order = 4, central = TRUE),
m1_rep = moment(h_rep, order = 1, central = FALSE),
m2_rep = moment(h_rep, order = 2, central = TRUE),
m3_rep = moment(h_rep, order = 3, central = TRUE),
m4_rep = moment(h_rep, order = 4, central = TRUE)) %>%
ungroup() %>%
pivot_longer(-.draw, names_sep = "_", names_to = c("moment", "rep")) %>%
ggplot(aes(value, color = rep)) +
# geom_histogram() +
geom_density() +
# facet_grid(laghbin ~ moment, scales = "free") +
facet_wrap(moment ~ ., scales = "free")
# Get moments of v
v_draws <- fit$draws("v_raw") %>% as_draws_matrix()
moments <-
v_draws %>%
as.matrix() %>%
t() %>%
as.data.frame() %>%
as_tibble() %>%
mutate(date = spx$date, s = h$median) %>%
mutate(sbin = lag(cut(s, quantile(s, seq(0, 1, by = 0.1))))) %>%
mutate(s = lag(s)) %>%
na.omit() %>%
pivot_longer(c(-date, -s, -sbin)) %>%
group_by(sbin, name) %>%
summarize(m1 = moment(value, order = 1, central = FALSE),
m2 = moment(value, order = 2, central = TRUE),
m3 = moment(value, order = 3, central = TRUE),
m4 = moment(value, order = 4, central = TRUE))
normal_moments <-
tibble(d = 1:(dim(v_draws)[2])) %>%
crossing(sbin = unique(moments$sbin)) %>%
mutate(value = rnorm(nrow(.))) %>%
group_by(sbin) %>%
summarize(m1 = moment(value, order = 1, central = FALSE),
m2 = moment(value, order = 2, central = TRUE),
m3 = moment(value, order = 3, central = TRUE),
m4 = moment(value, order = 4, central = TRUE)) %>%
pivot_longer(-sbin, names_to = "moment")
moments %>%
ungroup() %>%
pivot_longer(c(-sbin, -name), names_to = "moment") %>%
ggplot(aes(value)) +
geom_histogram() +
facet_grid(sbin ~ moment, scales = "free") +
geom_vline(aes(xintercept = value), color = "red", data = normal_moments)
# Plot moments of y and v versus rep
hvy_samples <-
fit$draws(c("h", "v", "y_rep")) %>%
as_draws_df() %>%
as_tibble() %>%
select(-.chain, -.iteration) %>%
pivot_longer(-.draw) %>%
mutate(var = str_extract(name, "[a-z]+")) %>%
mutate(idx = parse_number(name)) %>%
select(-name) %>%
pivot_wider(names_from = var, values_from = value)
hvy_samples %>%
rename(y_rep = y) %>%
inner_join(transmute(spx, date, idx = row_number(), y)) %>%
filter(idx > 1) %>%
arrange(.draw, date) %>%
group_by(.draw) %>%
mutate(hbin = cut(h, quantile(h, seq(0, 1, by = 0.25)), labels = 1:4)) %>%
mutate(laghbin = lag(hbin)) %>%
na.omit() %>%
ungroup() %>%
group_by(.draw, laghbin) %>%
summarize(m1_true = moment(y, order = 1, central = FALSE),
m2_true = moment(y, order = 2, central = TRUE),
m3_true = moment(y, order = 3, central = TRUE),
m4_true = moment(y, order = 4, central = TRUE),
m1_rep = moment(y_rep, order = 1, central = FALSE),
m2_rep = moment(y_rep, order = 2, central = TRUE),
m3_rep = moment(y_rep, order = 3, central = TRUE),
m4_rep = moment(y_rep, order = 4, central = TRUE)) %>%
ungroup() %>%
pivot_longer(c(-.draw, -laghbin), names_sep = "_", names_to = c("moment", "rep")) %>%
ggplot(aes(value, color = rep)) +
# geom_histogram() +
geom_density() +
# facet_grid(laghbin ~ moment, scales = "free") +
facet_wrap(laghbin + moment ~ ., scales = "free")
hvy_samples %>%
rename(y_rep = y) %>%
inner_join(transmute(spx, date, idx = row_number(), y)) %>%
mutate(v_rep = rnorm(nrow(.))) %>%
filter(idx > 1) %>%
arrange(.draw, date) %>%
group_by(.draw) %>%
mutate(hbin = cut(h, quantile(h, seq(0, 1, by = 0.25)), labels = 1:4)) %>%
mutate(laghbin = lag(hbin)) %>%
na.omit() %>%
ungroup() %>%
group_by(.draw, laghbin) %>%
summarize(m1_true = moment(v, order = 1, central = FALSE),
m2_true = moment(v, order = 2, central = TRUE),
m3_true = moment(v, order = 3, central = TRUE),
m4_true = moment(v, order = 4, central = TRUE),
m1_rep = moment(v_rep, order = 1, central = FALSE),
m2_rep = moment(v_rep, order = 2, central = TRUE),
m3_rep = moment(v_rep, order = 3, central = TRUE),
m4_rep = moment(v_rep, order = 4, central = TRUE)) %>%
ungroup() %>%
pivot_longer(c(-.draw, -laghbin), names_sep = "_", names_to = c("moment", "rep")) %>%
ggplot(aes(value, color = rep)) +
# geom_histogram() +
geom_density() +
# facet_grid(laghbin ~ moment, scales = "free") +
facet_wrap(laghbin + moment ~ ., scales = "free")
# Generate horsehose draws
N <- 1e6; c2 <- 1; tau <- 3; nu <- 5;
tibble(l2 = rcauchy(N)^2) %>%
mutate(lt = sqrt((c2*l2) / (c2+tau^2*l2))) %>%
mutate(v1 = rt(N, df = nu)*tau*lt) %>%
# mutate(v1 = rnorm(N)*tau*lt) %>%
mutate(v2 = rnorm(N)) %>%
select(v1, v2) %>%
mutate(i = row_number()) %>%
pivot_longer(-i) %>%
ggplot(aes(value, color = name)) +
# geom_histogram() +
geom_density() +
xlim(-5, 5)
e# facet_grid(name ~ .)
# scale_y_sqrt()
N <- 1e5
tibble(i = 1:N,
x = rnorm(N)) %>%
mutate(y = 0.3*pmin(0, x - -0.67) + x) %>%
pivot_longer(-i) %>%
ggplot(aes(value)) +
geom_histogram(binwidth = 0.1) +
facet_grid(name ~ .)
###### Play with weeks LOO
my.loglikelihood <- function(z, mu, logsigma, logdf) {
n <- length(z)
df <- exp(logdf)
sigma <- exp(logsigma)
LL <- -(n/2)*log(pi) + n*lgamma((df+1)/2) - n*lgamma(df/2) - (n/2)*log(df) -
n*log(sigma) - ((df+1)/2)*sum(log(1 + (1/df)*((z-mu)/sigma)^2))
LL
}
my.MLE <- function(z, df) {
NEGLOGLIKE <- function(par) { -my.loglikelihood(z, par[1], par[2], log(df)) }
PAR0 <- c(mean(z), log(sd(z)))
OPTIM <- optim(fn = NEGLOGLIKE, par = PAR0)
PARHAT <- OPTIM$par
MLE <- c(PARHAT[1], exp(PARHAT[2]))
MLE
}
my.MLE(x, df = 1)
sd5 <- rollify(sd, 5)
mabs5 <- rollify(function(x) mean(abs(x)), 5)
spx %>%
select(year, week, day, y) %>%
crossing(holdout = c("Mon", "Tue", "Wed", "Thu", "Fri")) %>%
arrange(year, week, holdout, day) %>%
group_by(year, week, holdout) %>%
filter(any(day == holdout)) %>%
filter(day != holdout) %>%
# summarize(n = n(), m = mean(y), s = sd(y)) %>%
summarize(n = n(), m = median(y), b = mean(abs(y-m))) %>%
# summarize(n = n(), m = my.MLE(y, 1)[1], s = my.MLE(y, 1)[2]) %>%
ungroup() %>%
inner_join(select(spx, year, week, holdout = day, y)) %>%
# mutate(p = pnorm(y, m, s)) %>%
mutate(p = plaplace(y, m, b)) %>%
# mutate(p = pt2(y, m, s, 1)) %>%
pull(p) %>% qplot(binwidth = 0.01)
spx %>%
mutate(s = lag(sd5(y)), b = lag(mabs5(y))) %>%
na.omit() %>%
mutate(x = rnorm(nrow(.), 0.1, s),
xl = rlaplace(nrow(.), 0.1, b)) %>%
mutate(sbin = cut(s, quantile(s, c(0.0, 0.25, 0.5, 0.75, 1.0)))) %>%
mutate(sbin = lag(sbin)) %>%
na.omit() %>%
select(date, x, y, xl, sbin) %>%
pivot_longer(c(x, y, xl)) %>%
ggplot(aes(value, color = name)) +
geom_histogram() +
facet_grid(name ~ sbin, scales = "free") +
scale_y_sqrt()
y <-
spx %>%
mutate(s = lag(sd5(y)), b = lag(mabs5(y))) %>%
na.omit() %>%
mutate(x = rnorm(nrow(.), 0.1, s),
xl = rlaplace(nrow(.), 0.1, b)) %>%
mutate(sbin = cut(s, quantile(s, c(0.0, 0.25, 0.5, 0.75, 1.0)))) %>%
mutate(sbin = lag(sbin)) %>%
na.omit() %>%
select(date, x, y, xl, sbin) %>%
# filter(sbin == "(0.053,0.517]") %>%
# filter(sbin == "(1.25,9.59]") %>%
group_split(sbin)
model <- cmdstan_model("stan/normal_mixture.stan")
init <-
replicate(4, list(theta = c(0.5, 0.4, 0.1),
mu = c(0.1, 0.0, 0.0),
sigma = c(0.1, 0.5, 2)), simplify = FALSE)
fit_wrapper <- function(i) {
model$sample(
data = list(K = 3, N = nrow(y[[i]]), y = y[[i]]$y),
seed = 1994,
iter_warmup = 5e2,
iter_sampling = 5e2,
parallel_chains = 4,
init = init
)
}
fits %>%
map(function(fit) fit$summary("sigma")) %>%
map2_dfr(1:length(.), function(df, i) mutate(df, i = i)) %>%
ggplot(aes(i, median)) +
geom_pointrange(aes(ymin = q5, ymax = q95)) +
facet_grid(variable ~ ., scales = "free")
fits %>%
map(function(fit) fit$summary("sigma")) %>%
map2_dfr(1:length(.), function(df, i) mutate(df, i = i)) %>%
ggplot(aes(i, median, color = variable)) +
geom_pointrange(aes(ymin = q5, ymax = q95)) +
scale_y_log10() +
geom_smooth(method = "lm", se = FALSE)
y_rep <-
fit$draws("y_rep") %>%
as_draws_df() %>%
as_tibble() %>%
sample_n(3) %>%
select(-.chain, -.iteration) %>%
pivot_longer(-.draw) %>%
bind_rows(tibble(.draw = -1, name = "y", value = y))
y_rep %>%
ggplot(aes(value)) +
geom_histogram() +
facet_wrap(.draw ~ .)
####################
model <- cmdstan_model("stan/sv5.stan")
K <- 3
init <-
replicate(4, list(phi = 0.98,
sigma = 0.3,
a_theta = rep(0.0, K), b_theta = rep(0.0, K),
a_m = rep(0.0, K), b_m = rep(0.0, K),
a_s = 1:K,
v = rep(0.0, nrow(spx))), simplify = FALSE)
init <-
replicate(4, list(phi = 0.98,
sigma = 0.3,
mu = c(0, 0, 0),
theta = c(0.45, 0.45, 0.1),
a_s = 1:K,
v = rep(0.0, nrow(spx))), simplify = FALSE)
fit <-
model$sample(
data = list(K = 3, T = nrow(spx), y = spx$y),
seed = 1994,
iter_warmup = 5e2,
iter_sampling = 5e2,
chains = 4,
parallel_chains = 4,
refresh = 10,
max_treedepth = 5,
adapt_delta = 0.5,
init = init
)
fit$summary() %>% print(n = 15)
fit$summary("h") %>%
bind_cols(spx) %>%
ggplot(aes(date, median)) +
geom_line() +
geom_ribbon(aes(ymin = q5, ymax = q95), alpha = 0.2)
s <- fit$summary("s")
s %>%
mutate(i = as.integer(str_extract(variable, "(?<=\\[)[0-9]+"))) %>%
mutate(k = as.integer(str_extract(variable, "(?<=,)[0-9]+"))) %>%
select(i, k, median, q5, q95) %>%
inner_join(transmute(spx, i = row_number(), date)) %>%
ggplot(aes(date, median, color = factor(k))) +
geom_line() +
scale_y_log10()
|
47f7fe044d6abac35bd982a36f99f793e1fc1c0f | 9855d52b68287ce333abcaa1fcb814e2ec0fd822 | /data-raw/industry.R | e42dd63c290a9e4471374ce5123d05b3dd712c38 | [
"MIT"
] | permissive | sunsiyu/featurer | 5f99e49216a0ad40334125694f3dc95feb849d23 | 0f6e8de8b13a4f8999df6aaf099c8b0f95205b45 | refs/heads/master | 2020-04-06T05:03:31.707118 | 2016-07-10T18:09:57 | 2016-07-10T18:09:57 | 56,992,050 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 862 | r | industry.R | allindustries <- c(
"Accommodations",
"Accounting",
"Advertising",
"Aerospace",
"Agriculture",
"AirTransportation",
"Apparel",
"Accessories",
"Auto",
"Banking",
"Beauty",
"Cosmetics",
"Biotechnology",
"Chemical",
"Communications",
"Computer",
"Construction",
"Consulting",
"ConsumerProducts",
"Education",
"Electronics",
"Employment",
"Energy",
"Entertainment",
"Fashion",
"FinancialServices",
"Food",
"Beverage",
"Health",
"Information",
"InformationTechnology",
"Insurance",
"Journalism",
"News",
"LegalServices",
"Manufacturing",
"Media",
"Broadcasting",
"MedicalDevices",
"Supplies",
"MotionPictures",
"Video",
"Music",
"Pharmaceutical",
"PublicAdministration",
"PublicRelations",
"Publishing",
"RealEstate",
"Retail",
"Service",
"Sports",
"Technology",
"Telecommunications",
"Tourism",
"Transportation",
"Travel",
"Utilities",
"VideoGame",
"WebServices"
)
|
81fb61a7c0240ed0beb728b31cf193ab89c54e44 | c9e0c41b6e838d5d91c81cd1800e513ec53cd5ab | /man/gtkCTreeSortNode.Rd | 3ac9085170e858bd986849e64b493c04b0ccd3a4 | [] | no_license | cran/RGtk2.10 | 3eb71086e637163c34e372c7c742922b079209e3 | 75aacd92d4b2db7d0942a3a6bc62105163b35c5e | refs/heads/master | 2021-01-22T23:26:26.975959 | 2007-05-05T00:00:00 | 2007-05-05T00:00:00 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 514 | rd | gtkCTreeSortNode.Rd | \alias{gtkCTreeSortNode}
\name{gtkCTreeSortNode}
\title{gtkCTreeSortNode}
\description{
Sort the children of a node. See \code{\link{GtkCList}} for how to set the sorting
criteria etc.
\strong{WARNING: \code{gtk_ctree_sort_node} is deprecated and should not be used in newly-written code.}
}
\usage{gtkCTreeSortNode(object, node)}
\arguments{
\item{\code{object}}{[\code{\link{GtkCTree}}] }
\item{\code{node}}{[\code{\link{GtkCTreeNode}}] }
}
\author{Derived by RGtkGen from GTK+ documentation}
\keyword{internal}
|
8e42263c9125b0309e6b73712b77d8629ab69a97 | f6513b202b9ad00cf073c891f99f5cd0af74cb48 | /R/gameprediction.R | 03c8cbf98fe5a3901b70ea85246221325f477df0 | [
"MIT"
] | permissive | zecellomaster/SoccerEloForecast | a24a0d9a7e5d5e9a49068177d4d1b70e661a870d | 73c3f0f67fbafebe73e2988153f47c607d3fc111 | refs/heads/master | 2023-03-29T17:32:41.837944 | 2021-03-27T01:23:10 | 2021-03-27T01:23:10 | 351,920,661 | 1 | 0 | null | null | null | null | UTF-8 | R | false | false | 3,457 | r | gameprediction.R | #Name: gameprediction.R
#Author: zecellomaster
#Date: 03/17/21 (v1.0)
#' Returns simulated match results or a list of the % chance of a win/loss/draw
#' of the higher Elo team (Team A).
#'
#' @import stats
#'
#' @param function_mode String or int; which mode should the function run: "chances"
#' or the number of matches to be simulated (Default = "chances": 15,000 simulations)
#'
#' @param elos vector; current Elo ratings of Teams A and B respectively
#'
#' @param home vector of booleans; Whether or not either team is at home
#'
#' @param prev_matches List of Dataframe; contains previous matches, Elo ratings,
#' and (if available) match weights of Teams A and B respectively.
#' Dataframe columns: team_elo, opp_elo, team_score, opp_score, team_home, opp_home,
#' match_weight
#'
#' @return Win%/Draw%/Loss% of Team A or Simulated Match Results
#'
#' @export
gameprediction <- function(function_mode = "chances", elos, home, prev_matches){
if (is.numeric(function_mode) == TRUE){
num_sims <- function_mode
}else if (function_mode == "chances"){
num_sims <- 15000
a_win <- 0
b_win <- 0
}else{
stop("Error. Please enter the number of game simulations you would like to
perform or \"chances\" to caluclate the odds of Team A's results")
}
reg_data <- poissonregression(elos,home,prev_matches)
#Here, the function returns lambda_a and b_reg. lambda_b will depend on lambda_a via
#b_reg
if (reg_data[[1]]== 1){
lambda_a <- reg_data[[2]]
goals <- data.frame(a_goals = rpois(num_sims, lambda_a))
b_reg <- reg_data[[3]]
for (i in 1:num_sims){
lambda_b <- exp(coef(b_reg)["(Intercept)"] + (coef(b_reg)["opp_elo"]*elos[2]) +
coef(b_reg)["opp_score"]*goals[i,"a_goals"])
goals[i,"b_goals"] <- rpois(1,lambda_b)
if(function_mode == "chances"){
if(goals[i,"a_goals"] > goals[i,"b_goals"]){
a_win = a_win + 1
}else if(goals[i,"a_goals"] < goals[i,"b_goals"]){
b_win = b_win + 1
}
}
}
} else if (reg_data[[1]] == 2){
lambda_a <- reg_data[[2]]
lambda_b <- reg_data[[3]]
goals <- data.frame(a_goals = rpois(num_sims,lambda_a),
b_goals = rpois(num_sims,lambda_b))
for(i in 1:dim(goals)[1]){
if(function_mode == "chances"){
if (goals[i,"a_goals"] > goals[i,"b_goals"]){
a_win <- a_win + 1
}else if (goals[i,"a_goals"] < goals[i,"b_goals"]){
b_win <- b_win + 1
}
}
}
} else if (reg_data[[1]] == 3){
lambda_a <- reg_data[[2]]
goals <- data.frame(a_goals = rpois(num_sims, lambda_a))
lambda_b1 <- reg_data[[3]]
b_reg <- reg_data[[4]]
l_weight <- reg_data[[5]]
for (i in 1:num_sims){
lambda_b2 <- exp(coef(b_reg)["(Intercept)"] + (coef(b_reg)["opp_elo"]*elos[2]) +
coef(b_reg)["opp_score"]*goals[i,"a_goals"])
lambda_bavg <- ((lambda_b1*(1-l_weight)) + (lambda_b2 * l_weight))/2
goals[i,"b_goals"] <- rpois(1,lambda_bavg)
if(function_mode == "chances"){
if(goals[i,"a_goals"] > goals[i,"b_goals"]){
a_win = a_win + 1
}else if(goals[i,"a_goals"] < goals[i,"b_goals"]){
b_win = b_win + 1
}
}
}
}
if(function_mode == "chances"){ #returns odds of win, loss, or draw
return(list(a_win/num_sims, b_win/num_sims, (1 -(a_win/num_sims) - (b_win/num_sims))))
}else{
return(goals)
}
}
|
78bd4bc4c5975761f05af757ff5f0bfa0796456f | 0974cce1a019a2fe22b7fd453ac2ef73ce335cbc | /man/load_data.Rd | 155d646f3f276da44a4cf973f84f9b7f0e132f1f | [
"MIT"
] | permissive | cavargasru/globalrc | b8ee273ea21271132efaebe83214f7a28ce6939c | 75911c6a0c8c06b80643416f06b0830ab5ee48ce | refs/heads/main | 2023-08-06T09:43:33.344894 | 2021-09-15T20:49:25 | 2021-09-15T20:49:25 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | true | 611 | rd | load_data.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/load_variables.R
\name{load_data}
\alias{load_data}
\title{Load input data, including pr2ar, the PfPR, and the AM.}
\usage{
load_data(config, pr2ar_version, domain_extent, years)
}
\arguments{
\item{config}{Input configuration file name.}
\item{pr2ar_version}{Which version of the \code{pr2ar_mesh.csv} file.}
\item{domain_extent}{Bounding box that we compute within the MAP raster.}
\item{years}{Which years to do.}
}
\value{
A list with the loaded data.
}
\description{
Load input data, including pr2ar, the PfPR, and the AM.
}
|
c70b9887a42f19c2c8bf7cdd302e01a6378dc6b0 | d1ed371eee97ff630710ab30a942385fe92857c8 | /basic/map-china/plot.R | 3882367a0ff5d47293366e81ab542588bf5f472a | [
"CC-BY-3.0",
"LicenseRef-scancode-unknown-license-reference",
"AFL-2.1",
"AFL-3.0"
] | permissive | geng-lee/plugins-open | 7097fc237c9cab9ba8d1bf6f6c964b19837ae56c | 6151ca0e0b437cc5555a71ec4eacfa1354bbd8bd | refs/heads/master | 2022-12-17T06:21:24.486819 | 2020-09-27T14:45:33 | 2020-09-27T14:45:33 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 3,018 | r | plot.R | #######################################################
# China Map. #
#-----------------------------------------------------#
# Author: < Mingjie Wang > #
# Affiliation: Shanghai Hiplot Team #
# Website: https://hiplot.com.cn #
# #
# Date: 2020-04-10 #
# Version: 0.1 #
#######################################################
# CAUTION #
#-----------------------------------------------------#
# Copyright (C) 2020 by Hiplot Team #
# All rights reserved. #
#######################################################
pacman::p_load(maptools)
pacman::p_load(maps)
############# Section 1 ##########################
# input options, data and configuration section
##################################################
{
initial_options <- commandArgs(trailingOnly = FALSE)
file_arg_name <- "--file="
script_name <- sub(
file_arg_name, "",
initial_options[grep(file_arg_name, initial_options)]
)
script_dir <- dirname(script_name)
source(sprintf("%s/../lib.R", script_dir))
source(sprintf("%s/../head.R", script_dir))
# read in data file
usr_cnames <- colnames(data)
colnames(data) <- c("name", "value")
# read in map data
china_map <- rgdal::readOGR(sprintf("%s/china.shp", script_dir))
# extract province information from shap file
china_province <- setDT(china_map@data)
setnames(china_province, "NAME", "province")
# transform to UTF-8 coding format
china_province[, province := iconv(province, from = "GBK", to = "UTF-8")]
# create id to join province back to lat and long, id = 0 ~ 924
china_province[, id := .I - 1]
# there are more shapes for one province due to small islands
china_province[, province := as.factor(province)]
dt_china <- setDT(fortify(china_map))
dt_china[, id := as.numeric(id)]
setkey(china_province, id)
setkey(dt_china, id)
dt_china <- china_province[dt_china]
# set input data
data <- data.table(data)
setkey(data, name)
setkey(dt_china, province)
china_map_pop <- data[dt_china]
}
############# Section 2 #############
# plot section
#####################################
{
p <- ggplot(
china_map_pop,
aes(x = long, y = lat, group = group, fill = value)
) +
labs(fill = usr_cnames[2]) +
geom_polygon() +
geom_path() +
scale_fill_gradientn(colours = colorpanel(75,
low = "darkgreen",
mid = "yellow", high = "red"
), na.value = "grey10") +
ggtitle(conf$general$title)
## set theme
theme <- conf$general$theme
p <- choose_ggplot_theme(p, theme)
}
############# Section 3 #############
# output section
#####################################
{
export_single(p, opt, conf)
source(sprintf("%s/../foot.R", script_dir))
}
|
26041e239c87fb280fea6fb5b9d28d3c7e5b9517 | cd73a0a038e0c0983ed20ce02a9f30fe5b47dc78 | /man/plot.superSeq.Rd | e979e936ce28ed974649a0e0009b67a406eab2a0 | [
"MIT"
] | permissive | StoreyLab/superSeq | 35e2359e64e409d02a4b58ce81eeaf62f86654a0 | 52c287dae1c9daa6c141fa866dc2536298c8b815 | refs/heads/master | 2020-05-21T02:35:00.692786 | 2019-05-13T19:23:15 | 2019-05-13T19:23:15 | 185,881,979 | 13 | 1 | null | null | null | null | UTF-8 | R | false | true | 352 | rd | plot.superSeq.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/plot-superSeq.R
\name{plot.superSeq}
\alias{plot.superSeq}
\alias{plot,}
\title{Plotting for superSeq object}
\usage{
\method{plot}{superSeq}(x, ...)
}
\arguments{
\item{x}{superSeq object}
\item{...}{not used}
}
\description{
Plotting for superSeq object
}
\keyword{plot}
|
eed6f29262f9094bc807a9a32a3c20e047942a07 | 0f91cbac74fcd5186311af4363f1c8e7fadefca7 | /R/hello.R | 669febd48baed3f4b3d808ad0267fe55c32d6da3 | [] | no_license | MichaelbGordon/PooledMarketR | e8df56112f62826e60fe517c7034c612fd1436a3 | 34270889d9fbff62b07a996271988ba2c8c0e9b3 | refs/heads/master | 2020-05-19T15:27:50.059836 | 2019-06-10T19:54:38 | 2019-06-10T19:54:38 | 185,085,454 | 5 | 0 | null | null | null | null | UTF-8 | R | false | false | 728 | r | hello.R | # Hello, world!
#
# This is an example function named 'hello'
# which prints 'Hello, world!'.
#
# You can learn more about package authoring with RStudio at:
#
# http://r-pkgs.had.co.nz/
#
# Some useful keyboard shortcuts for package authoring:
#
# Build and Reload Package: 'Cmd + Shift + B'
# Check Package: 'Cmd + Shift + E'
# Test Package: 'Cmd + Shift + T'
# library(tidyverse)
# pm_data <- read_rds('/Users/mbgordon/Dropbox/Michael_shared/pooled\ market/Final\ Data/Pooled_Market_Data_full_set.rds')
# save(pm_data,file = 'data/pm_data.RData')
#
# load(file = 'data/PM_data.RData')
# library(devtools)
# t <- PooledMarketR::object
# t <- PM_data
# build()
#t <- PooledMarketR::pm_data
|
ec9a41a6256e3d8cbaa2acdf91e1ce6d2af70522 | d129aca2797ec95826d5dd639a0254f29647bba4 | /makeCacheMatrix.R | f3efb0b633d2eb9c38d52de06ba49065830d66fd | [] | no_license | 200002466/ProgrammingAssignment2 | cc3772256df83c35619a9066837712b0f417c193 | 37fdb7f117bbe97b22f30d15a2e0cd5980088b35 | refs/heads/master | 2020-12-25T12:39:34.260487 | 2015-08-23T22:16:27 | 2015-08-23T22:16:27 | 41,263,574 | 0 | 0 | null | 2015-08-23T19:21:18 | 2015-08-23T19:21:17 | null | UTF-8 | R | false | false | 1,480 | r | makeCacheMatrix.R | makeCacheMatrix <- function(matrix_1 = numaric()) {
## The function make Cache Matrix creates a special matrix object
## that can cache its inverse.
##
## ******** Define Input Variables ********************
## matrix_1 is a square invertabl matrix
##
## ******* Define Local Varriables ******************
## matrix_inverse_1 is the inverse of the matrix_1
##
##
## ******* Define parent Varriables ******************
## matrix_2 .
## matrix_inverse_2 is a logical varible T/F
##
##
matrix_inverse_2 <- NULL
##
## set the value of the matrix
set <- function(matrix_2) {
## the <<- rebinds an existing name in the parent of the current enveiroment.
matrix_1 <<- matrix_2
matrix_inverse_2 <<- NULL
} ## End of function set ************************************
##
## get the value of the matrix.
get <- function() matrix_1
##
## set the value of the inverse here and in the parent enviroment.
setinverse <- function(matrix_inverse_1) matrix_inverse_2 <<- matrix_inverse_1
##
## get the value of the inverse
getinverse <- function() matrix_inverse_2
##
## the following lines stores the 4 functions.
list(set = set,
get = get,
setinverse = setinverse,
getinverse = getinverse)
##
} ## End of Function makeCacheMatrix *****************************
|
fb2eb3b42a50e3ac6fcbe1383589892f2a0cd48a | 5ac5920bc54c456669b9c1c1d21ce5d6221e27eb | /facebook/delphiFacebook/man/compute_multiple_choice.Rd | 6c804d5c7956725579b7ab99ca8cba6135cf3d5f | [
"MIT"
] | permissive | alexcoda/covidcast-indicators | 50e646efba61fbfe14fd2e78c6cf4ffb1b9f1cf0 | 0c0ca18f38892c850565edf8bed9d2acaf234354 | refs/heads/main | 2023-08-13T04:26:36.413280 | 2021-09-16T18:16:08 | 2021-09-16T18:16:08 | 401,882,787 | 0 | 0 | MIT | 2021-09-01T00:41:47 | 2021-09-01T00:41:46 | null | UTF-8 | R | false | true | 1,083 | rd | compute_multiple_choice.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/contingency_calculate.R
\name{compute_multiple_choice}
\alias{compute_multiple_choice}
\title{Return multiple choice response estimates. Val is the number of people
represented by the survey respondents in a given response.}
\usage{
compute_multiple_choice(response, weight, sample_size, total_represented)
}
\arguments{
\item{response}{a vector of multiple choice responses}
\item{weight}{a vector of sample weights for inverse probability weighting;
invariant up to a scaling factor}
\item{sample_size}{The sample size to use, which may be a non-integer (as
responses from ZIPs that span geographical boundaries are weighted
proportionately, and survey weights may also be applied)}
\item{total_represented}{Number of people represented in sample, which may
be a non-integer}
}
\value{
a list of named counts and other descriptive statistics
}
\description{
This function takes vectors as input and computes the response values
(a point estimate named "val" and a sample size
named "sample_size").
}
|
d9c8528a73e064dc3face20a879573190845fe6c | d406b9068f635eed507ed21f000aaa55e3ec034c | /man/nls_panel2.Rd | 02814258cd3a1b3fe3ed79403dff1a03fac75a0e | [] | no_license | Worathan/PoEdata | 273eab591e56b08252dff3f681c1c9e0b34f7d79 | d415eb1b776b04c29ee38d58bbbd1bf37ef92eb1 | refs/heads/master | 2020-04-20T11:10:02.167677 | 2019-02-02T08:35:48 | 2019-02-02T08:35:48 | 168,808,539 | 0 | 0 | null | 2019-02-02T07:53:41 | 2019-02-02T07:53:41 | null | UTF-8 | R | false | false | 1,710 | rd | nls_panel2.Rd | \name{nls_panel2}
\alias{nls_panel2}
\docType{data}
\title{
Nls_panel2 Data
}
\description{
obs: 1432 [2 year on 716 individuals]
}
\usage{data("nls_panel2")}
\format{
A data frame with 1432 observations on the following 26 variables.
\describe{
\item{\code{id}}{group(id)}
\item{\code{year}}{interview year}
\item{\code{lwage}}{ln(wage/GNP deflator)}
\item{\code{hours}}{usual hours worked}
\item{\code{age}}{age in current year}
\item{\code{educ}}{current grade completed}
\item{\code{collgrad}}{1 if college graduate}
\item{\code{msp}}{1 if married, spouse present}
\item{\code{nev_mar}}{1 if never yet married}
\item{\code{not_smsa}}{1 if not SMSA}
\item{\code{c_city}}{1 if central city}
\item{\code{south}}{1 if south}
\item{\code{black}}{1 if black}
\item{\code{union}}{1 if union}
\item{\code{exper}}{total work experience}
\item{\code{exper2}}{exper^2}
\item{\code{tenure}}{job tenure, in years}
\item{\code{tenure2}}{tenure^2}
\item{\code{dlwage}}{(lwage - lwage[_n-1])}
\item{\code{dexper}}{(exper - exper[_n-1])}
\item{\code{dtenure}}{(tenure - tenure[_n-1])}
\item{\code{dsouth}}{(south - south[_n-1])}
\item{\code{dunion}}{(union - union[_n-1])}
\item{\code{dexper2}}{(exper2 - exper2[_n-1])}
\item{\code{dtenure2}}{(tenure2 - tenure2[_n-1])}
\item{\code{d88}}{1 if year 1988}
}
}
\details{
This data is a subset of nls_panel containing only years 1987 and 1988
}
\source{
http://principlesofeconometrics.com/poe4/poe4.htm
}
\references{
%% ~~ possibly secondary sources and usages ~~
}
\examples{
data(nls_panel2)
## maybe str(nls_panel2) ; plot(nls_panel2) ...
}
\keyword{datasets}
|
3942d9c78fdcd12918a70b5824cda01d6f813ebc | 29585dff702209dd446c0ab52ceea046c58e384e | /cpgen/R/clmm.R | 107a54908fe5930d0284721133870f8137a0060b | [] | no_license | ingted/R-Examples | 825440ce468ce608c4d73e2af4c0a0213b81c0fe | d0917dbaf698cb8bc0789db0c3ab07453016eab9 | refs/heads/master | 2020-04-14T12:29:22.336088 | 2016-07-21T14:01:14 | 2016-07-21T14:01:14 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 13,421 | r | clmm.R | #
# clmm.R
# Claas Heuer, June 2014
#
# Copyright (C) 2014 Claas Heuer
#
# This file is part of cpgen.
#
# cpgen is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# cpgen is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# in file.path(R.home("share"), "licenses"). If not, see
# <http://www.gnu.org/licenses/>.
#
# clmm
clmm <- function(y, X = NULL , Z = NULL, ginverse = NULL, par_random = NULL, niter=10000, burnin=5000,scale_e=0,df_e=-2, beta_posterior = FALSE, verbose = TRUE, timings = FALSE, seed = NULL, use_BLAS=FALSE){
default_scale = 0
default_df = -2
h2 = 0.3
default_GWAS_window_size_proportion = 0.01
default_GWAS_threshold = 0.01
# renamed 'random' to Z in the R function
random = Z
allowed=c("numeric", "list")
a = class(y)
if(!a %in% allowed) stop("phenotypes must match one of the following types: 'numeric' 'list'")
if(class(y) == "list") {
p = length(y)
if (sum(unlist(lapply(y,is.vector))) != p) stop("phenotypes must be supplied as vectors")
n = unlist(lapply(y,length))
if (sum(n[1]!=n) > 0) stop("phenoytpe vectors must have same length")
n = n[1]
if(is.null(names(y))) names(y) <- paste("Phenotype_",1:p,sep="")
} else {
if(!is.vector(y)) stop("phenotype must be supplied as vector")
n <- length(y)
y <- list(y)
names(y) <- "Phenotype_1"
}
y <- lapply(y,as.numeric)
if(any(unlist(lapply(y,function(x)var(x,na.rm=TRUE)))==0)) stop("one or more phenotypes with 0 variance detected")
if(is.null(X)) {
X = array(1,dim=c(n,1))
par_fixed <- list(scale=default_scale,df=default_df,sparse_or_dense="dense", name="fixed_effects", method="fixed")
} else {
if(X_is_ok(X,n,"fixed")) {
if(class(X) == "matrix") { type = "dense" } else { type = "sparse" }
par_fixed <- list(scale=default_scale,df=default_df,sparse_or_dense=type,name="fixed_effects",method="fixed")
}
}
par_fixed$GWAS=FALSE
par_fixed$GWAS_threshold = 0.01
par_fixed$GWAS_window_size = 1
# added 09/2015 - ginverse
par_fixed$sparse_or_dense_ginverse = "dense"
par_random_all = list()
par_temp = par_random
if(is.null(random)) {
random = list()
par_random_all = list()
for(k in 1:length(y)) { par_random_all[[k]] = list(list()) }
} else {
if(is.null(names(random))) names(random) = paste("Effect_",1:length(random),sep="")
for(k in 1:length(y)) {
par_random=par_temp
if(is.null(par_random)) {
par_random<-list(length(random))
for(i in 1:length(random)){
if(X_is_ok(random[[i]],n,names(random)[i])) {
method = "ridge"
if(class(random[[i]]) == "matrix") type = "dense"
if(class(random[[i]]) == "dgCMatrix") type = "sparse"
par_random[[i]] = list(scale=default_scale,df=default_df,sparse_or_dense=type,method=method, name=as.character(names(random)[i]), GWAS=FALSE, GWAS_threshold = 0.01, GWAS_window_size = 1) }
}
} else {
if(length(par_random) != length(random)) stop(" 'par_effects' must have as many items as 'random' ")
for(i in 1:length(par_random)) {
if(!is.list(par_random[[i]])) par_random[[i]] <- list()
X_is_ok(random[[i]],n,names(random)[i])
allowed_methods = c("fixed","ridge","BayesA")
if(is.null(par_random[[i]]$method)) par_random[[i]]$method <- "ridge"
if(is.null(par_random[[i]]$name)) par_random[[i]]$name = as.character(names(random)[i])
if(!par_random[[i]]$method %in% allowed_methods) stop(paste("Method must be one of: ",paste(allowed_methods,collapse=" , "),sep=""))
if(is.null(par_random[[i]]$df[k]) | !is.numeric(par_random[[i]]$df[k]) | length(par_random[[i]]$df[k]) > 1) {
if(par_random[[i]]$method == "BayesA") {
par_random[[i]]$df = 4.0
} else {
par_random[[i]]$df = default_df
}
} else {
par_random[[i]]$df = par_random[[i]]$df[k]
}
if(is.null(par_random[[i]]$scale[k]) | !is.numeric(par_random[[i]]$scale[k]) | length(par_random[[i]]$scale[k]) > 1) {
if(par_random[[i]]$method == "BayesA") {
## Fernando et al. 2012
dfA = par_random[[i]]$df
meanVar = mean(ccolmv(random[[i]],compute_var=T))
varG = h2*var(y[[k]],na.rm=TRUE)
varMarker = varG / ncol(random[[i]]) * meanVar
par_random[[i]]$scale = varMarker * (dfA -2) / dfA
} else {
par_random[[i]]$scale = default_scale
}
} else {
par_random[[i]]$scale = par_random[[i]]$scale[k]
}
if(class(random[[i]]) == "matrix") { type = "dense" } else { type = "sparse" }
par_random[[i]]$sparse_or_dense = type
# GWAS
if(is.null(par_random[[i]]$GWAS)) {
par_random[[i]]$GWAS=FALSE
par_random[[i]]$GWAS_threshold = 0.01
par_random[[i]]$GWAS_window_size = 1
} else {
if(is.null(par_random[[i]]$GWAS$threshold)) {
par_random[[i]]$GWAS_threshold = default_GWAS_threshold
} else {
par_random[[i]]$GWAS_threshold = as.numeric(par_random[[i]]$GWAS$threshold)
}
if(is.null(par_random[[i]]$GWAS$window_size)) {
par_random[[i]]$GWAS_window_size = as.integer(ncol(random[[i]]) * default_GWAS_window_size_proportion)
} else {
par_random[[i]]$GWAS_window_size = as.integer(par_random[[i]]$GWAS$window_size)
}
par_random[[i]]$GWAS = TRUE
}
}
}
par_random_all[[k]] = par_random
}
}
################################
### added 09/2015 - Ginverse ###
################################
# first add the parameter "sparse_or_dense_ginverse" to the par_random list
for(i in 1:length(par_random_all)) {
for(j in 1:length(par_random_all[[i]])) par_random_all[[i]][[j]]$sparse_or_dense_ginverse = "sparse"
}
if(!is.null(ginverse)) {
if(length(ginverse)!= length(random)) stop("If provided, ginverse must have as many items as random. Put 'NULL' for no ginverse in the list for a particular random effect")
# check dimensions - all that matters is the number of columns
for(i in 1:length(ginverse)) {
if(!is.null(ginverse[[i]])) {
if(ncol(ginverse[[i]]) != ncol(random[[i]])) stop(paste("Number of columns in design matrix: '",
par_random[[i]]$name,"' dont match dimnsion of corresponding ginverse", sep=""))
if(!class(ginverse[[i]]) %in% c("matrix","dgCMatrix")) stop(paste("Ginverse: '",par_random[[i]]$name,
"' must be of type 'matrix' or 'dgCMatrix'",sep=""))
# set the method for that effect - Only ridge regression allowed
# also set the type of matrix for ginverse
# this is crap - but good enough for now
for(j in 1:length(par_random_all)) {
par_random_all[[j]][[i]]$method = "ridge_ginverse"
par_random_all[[j]][[i]]$sparse_or_dense_ginverse = ifelse(class(ginverse[[i]])=="matrix", "dense", "sparse")
}
}
}
# if no ginverse in the list, create dummy
} else {
ginverse <- vector("list",length(random))
}
# RNG Seed based on system time and process id
# Taken from: http://stackoverflow.com/questions/8810338/same-random-numbers-every-time
if(is.null(seed)) { seed = as.integer((as.double(Sys.time())*1000+Sys.getpid()) %% 2^31) }
par_mcmc = list()
verbose_single = verbose
if(timings | length(y) > 1) verbose_single = FALSE
if(length(y)>1) {
if(length(scale_e)!=length(y)) scale_e = rep(scale_e[1], length(y))
if(length(df_e)!=length(y)) df_e = rep(df_e[1], length(y))
}
# for CV timings is not a good thing
if(length(y) > 1) timings = FALSE
for(i in 1:length(y)) {
par_mcmc[[i]] = list(niter=niter, burnin=burnin, full_output=beta_posterior, verbose=verbose_single,
timings = timings, scale_e = scale_e[i], df_e = df_e[i], seed = as.character(seed), name=as.character(names(y)[i]))
}
mod <- .Call("clmm",y, X , par_fixed ,random, par_random_all ,par_mcmc, verbose=verbose, options()$cpgen.threads, use_BLAS, ginverse, PACKAGE = "cpgen" )
if(length(y) == 1) { return(mod[[1]]) } else { return(mod) }
#return(list(y, X , par_fixed ,random, par_random_all ,par_mcmc, verbose=verbose, options()$cpgen.threads, use_BLAS, ginverse))
}
get_pred <- function(mod) {
return(matrix(unlist(lapply(mod,function(x)x$Predicted)),ncol=length(mod),nrow=length(mod[[1]]$Predicted)))
}
get_cor <- function(predictions,cv_pheno,y) {
cv_vec <- matrix(unlist(cv_pheno),nrow=length(y),ncol=length(cv_pheno),byrow=FALSE)
mean_pred <- rep(NA,nrow(predictions))
for(i in 1:nrow(predictions)) {
mean_pred[i] <- mean(predictions[i,which(is.na(cv_vec[i,]))])
}
return(cor(mean_pred,y,use="pairwise.complete.obs"))
}
# cGBLUP
cGBLUP <- function(y,G,X=NULL, scale_a = 0, df_a = -2, scale_e = 0, df_e = -2,niter = 10000, burnin = 5000, seed = NULL, verbose=TRUE){
isy <- (1:length(y))[!is.na(y)]
if(length(y) != nrow(G)) stop("dimension of y and G dont match")
if(verbose) cat("\nComputing Eigen Decomposition\n")
if(length(isy) < length(y)) {
UD <- eigen(G[isy,isy]) } else {
UD <- eigen(G) }
n <- length(isy)
if(is.null(X)) X = rep(1,length(y[isy]))
Uy <- (t(UD$vectors)%c%y[isy])[,1]
UX <- t(UD$vectors)%c%X
D_sqrt <- sqrt(UD$values)
Z<-sparseMatrix(i=1:n,j=1:n,x=D_sqrt)
par_random <- list(list(scale=scale_a,df=df_a,sparse_or_dense="sparse",method="ridge"))
if(verbose) cat("Running Model\n")
if(is.null(seed)) { seed = as.integer((as.double(Sys.time())*1000+Sys.getpid()) %% 2^31) }
# set the number of threads to 1 for clmm
old_threads <- get_num_threads()
set_num_threads(1,silent=TRUE)
mod <- clmm(y = Uy, X = UX , Z = list(Z), par_random = par_random, scale_e=scale_e, df_e=df_e, verbose=verbose, niter=niter, burnin=burnin, seed=seed)
# set number of threads to old value
set_num_threads(old_threads,silent=TRUE)
u <- rep(NA,length(y))
u[isy] <- UD$vectors %c% (D_sqrt * mod[[4]]$posterior$estimates_mean)
if(length(isy) < length(y)) { u[-isy] <- G[-isy,isy] %c% csolve(G[isy,isy],u[isy]) }
e<-mod$Residual_Variance$Posterior
return(list(var_e = mod$Residual_Variance$Posterior_Mean,
var_a = mod[[4]]$posterior$variance_mean,
b = mod[[3]]$posterior$estimates_mean,
a = u,
posterior_var_e = mod$Residual_Variance$Posterior,
posterior_var_a = mod[[4]]$posterior$variance))
}
X_is_ok <- function(X,n,name) {
allowed=c("matrix","dgCMatrix")
a = class(X)
#if(sum(a%in%allowed)!=1) stop(paste(c("lol","rofl")))
if(sum(a%in%allowed)!=1) stop(paste("design matrix '",name,"' must match one of the following types: ",paste(allowed,collapse=" , "),sep=""))
if(anyNA(X)) { stop(paste("No NAs allowed in design matrix '", name,"'", sep="")) }
if(a=="matrix" | a=="dgCMatrix") { if(nrow(X) != n) stop(paste("Number of rows in design matrix '",name,"' doesnt match number of observations in y",sep="")) }
return(1)
}
### GWAS
#cGWAS.BR <- function(mod, M, window_size, threshold, sliding_window=FALSE, verbose=TRUE) {
#
# niter = mod$mcmc$niter
# burnin = mod$mcmc$burnin
#
# n_windows = ifelse(sliding_window, as.integer(ncol(M) - window_size + 1), as.integer(ncol(M) / window_size))
#
# posterior = mod[[4]]$posterior$estimates[(burnin+1):niter,]
#
# genetic_values = tcrossprod(M, posterior)
# genetic_variance = apply(genetic_values,2,var)
#
# res = array(0, dim=c(n_windows,6))
# colnames(res) <- c("window","mean_var","mean_var_proportion","prob_var_bigger_threshold","start","end")
# end=0
# count = 0
#
# for(i in 1:n_windows) {
#
# count = count + 1
# if(verbose) print(paste("window: ", i, " out of ", n_windows,sep=""))
# if(sliding_window) {
# start = count
# end = count + window_size - 1
# } else {
# start = end + 1
# end = end + window_size
# if(i == n_windows) end = ncol(M)
# }
#
# window_genetic_values = tcrossprod(M[,start:end], posterior[,start:end])
# window_genetic_variance = ccolmv(window_genetic_values,compute_var=TRUE)
# post_var_proportion = window_genetic_variance / genetic_variance
#
# res[i,"window"] = i
# res[i,"mean_var"] = mean(window_genetic_variance)
# res[i,"mean_var_proportion"] = mean(post_var_proportion)
# res[i,"prob_var_bigger_threshold"] = sum(post_var_proportion > threshold) / nrow(posterior)
# res[i,"start"] = start
# res[i,"end"] = end
#
# }
#
# return(res)
#
#}
|
417e9f785a4c0cdaef7d126c3a671eead57d2503 | 6e0ea601537671eecba6a0f50e24d4784d692584 | /R/RobustScores.R | d2842bde66e76301c8e3bac5bf032297ba8d11b0 | [] | no_license | GiulioCostantini/IATscores | 35fb6569d654f2f15d39760ca88ff0ca8b8984a8 | b7b38d7ba3bda4be3975fcf73a58e1a0ca8b7911 | refs/heads/master | 2021-01-10T02:48:59.513457 | 2020-05-09T16:59:13 | 2020-05-09T16:59:13 | 24,192,714 | 0 | 1 | null | 2020-05-02T11:14:25 | 2014-09-18T15:05:56 | R | UTF-8 | R | false | false | 5,864 | r | RobustScores.R | RobustScores <- function(IATdata,
P1 = c("none", "fxtrim", "fxwins", "trim10", "wins10",
"inve10"),
P2 = c("ignore", "exclude", "recode", "separate",
"recode600"),
P3 = c("dscore", "gscore", "wpr90", "minid",
"minid_t10", "minid_w10", "minid_i10"),
P4 = c("nodist", "dist"),
maxMemory = 1000, verbose = TRUE,
autoremove = TRUE)
{
select <- dplyr::select
filter <- dplyr::filter
mincor <- 3 # minimum number of correct responses with lat < k10
# required to be included int he analyses
# maximum allowed latency. Careful, if change here,
# consider changing the followint fixed parameters also in function doP1P2
k10 <- 10000
upfxtrim <- 10000
lofxtrim <- 400
k10 <- min(k10, upfxtrim)
# CHECK THE INPUT
# column subject must be present and must be numeric
if(!"subject" %in% names(IATdata))
stop('Bad input IATdata: Column "subject" is missing')
if(!is.numeric(IATdata$subject))
warning('Bad input IATdata: Column "subject" must be numeric',
immediate. = TRUE)
# column subject must be present and must be numeric
if(!"latency" %in% names(IATdata))
{
stop('Bad input IATdata: Column "latency" is missing')
} else if(!is.numeric(IATdata$latency))
{
stop('Bad input IATdata: Column "latency" must be numeric')
}
# column correct must be present and binary numerical (0,1) or logical
if(!"correct" %in% names(IATdata))
{
stop('Bad input IATdata: Column "correct" is missing')
} else if(!is.logical(IATdata$correct) &! is.numeric(IATdata$correct))
{
stop('Bad input IATdata: Column "correct" must be logical or binary')
} else if (is.numeric(IATdata$correct) & !all(IATdata$correct %in% c(0,1)))
{
stop('Bad input IATdata: Column "correct" must be logical or binary')
}
# column blockcode must be present and include only values pair1 and pair2
if(!"blockcode" %in% names(IATdata))
{
stop('Bad input IATdata: Column "blockcode" is missing')
}
# praccrit is optional, however if absent, P4 can only be "nodist"
if(!"praccrit" %in% names(IATdata) & ("dist" %in% P4))
{
P4 <- "nodist"
warning('PARAMETER P4 HAS BEEN SET TO "nodist".
Parameter P4 includes option "dist", distinction between practice
and critical blocks. However column praccrit, which would allow
to distinguish between practice and critical blocks, is not
specified in the input IATdata.', immediate. = TRUE)
IATdata$praccrit <- NA
}
# SELECT COLUMNS
# drop any irrelevant (and potentially dangerous) column ...
IATdata <- select(IATdata, subject, latency, correct, blockcode, praccrit)
# ... and row
IATdata <- filter(IATdata, blockcode == "pair1" | blockcode == "pair2")
# define a useful univocal index by row
IATdata$index <- 1:nrow(IATdata)
# Exclude participants with less than 3 correct valid latencies (< 10s and
# > 400ms), in each block
ncor <- group_by(IATdata, subject, blockcode) %>%
summarize(ncor = sum(!is.na(correct) & correct == TRUE &
!is.na(latency) & latency < k10 &
latency >= lofxtrim)) %>%
filter(ncor < mincor)
if(autoremove & nrow(ncor) != 0)
{
IATdata <- filter(IATdata, !subject %in% ncor$subject)
warning(paste("The following subjects have been removed because they
have too few correct responses to compute IAT scores, i.e.,
less than", mincor, "correct responses with latency less than",
k10, "ms and more than", lofxtrim, "ms in at least one block:
Subjects =", str_c(ncor$subject, collapse = ", ")),
immediate. = TRUE)
}
# COMPUTE THE ROBUST IAT SCORES
Scores <- doP1P2P3P4(IATdata, P1 = P1, P2 = P2, P3 = P3, P4 = P4,
maxMemory = maxMemory, verbose = verbose)
if(verbose) print(paste0(Sys.time(), ": IAT scores have been computed"))
Scores
}
# D2 scores
D2 <- function(IATdata,...) RobustScores(IATdata,
P1 = "fxtrim",
P2 = "ignore",
P3 = "dscore",
P4 = "dist", ...)
# D5 scores
D5 <- function(IATdata,...) RobustScores(IATdata,
P1 = "fxtrim",
P2 = "recode",
P3 = "dscore",
P4 = "dist", ...)
# D6 scores
D6 <- function(IATdata,...) RobustScores(IATdata,
P1 = "fxtrim",
P2 = "recode600",
P3 = "dscore",
P4 = "dist", ...)
# D2SWND scores
D2SWND <- function(IATdata,...) RobustScores(IATdata,
P1 = "wins10",
P2 = "ignore",
P3 = "dscore",
P4 = "nodist", ...)
# D5SWND scores
D5SWND <- function(IATdata,...) RobustScores(IATdata,
P1 = "wins10",
P2 = "recode",
P3 = "dscore",
P4 = "nodist", ...)
# D6SWND scores
D6SWND <- function(IATdata,...) RobustScores(IATdata,
P1 = "wins10",
P2 = "recode600",
P3 = "dscore",
P4 = "nodist", ...)
|
dbc9645dacf707b0c5f11d77b1ab500c168180ab | c657d3786e9620369e96ca5e19e2923c390e2f37 | /koond/yld.R | a05c7d0e4911287efbbbffeb6705063a0fdaabf5 | [] | no_license | AndresVork/Rita2 | cf865f7ae0ef921fca6414d8590ea508ea046b78 | a8adedb9d5558a3fe042593c3ddb50c59b07ebc4 | refs/heads/master | 2023-01-13T18:48:34.562971 | 2020-11-14T09:12:21 | 2020-11-14T09:12:21 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 2,428 | r | yld.R | ##############################################
# Üldandmed meedet kasutanud ettevõtte kohta
#
# (c) 2020 - Raoul Lättemäe
#
##############################################
library(tidyverse)
# Lae käibe- ja statistikanumbrid
load("~/Dokumendid/R/EMTA/2019-2020.rdata")
andmed$Käive.2019 = rowSums(andmed[,c("Käive.i.2019", "Käive.ii.2019", "Käive.iii.2019", "Käive.iv.2019")], na.rm = TRUE)
andmed$Maksud.2019 = rowSums(andmed[,c("Maksud.i.2019", "Maksud.ii.2019", "Maksud.iii.2019", "Maksud.iv.2019")], na.rm = TRUE)
andmed$Tööjõumaksud.2019 = rowSums(andmed[,c("Tööjõumaksud.i.2019", "Tööjõumaksud.ii.2019", "Tööjõumaksud.iii.2019", "Tööjõumaksud.iv.2019")], na.rm = TRUE)
andmed$Töötajad.2019 = rowSums(andmed[,c("Töötajad.i.2019", "Töötajad.ii.2019", "Töötajad.iii.2019", "Töötajad.iv.2019")], na.rm = TRUE)/4
andmed$Käive.i = rowSums(andmed[c("Käive.i.2020")], na.rm = TRUE) - rowSums(andmed[c("Käive.i.2019")], na.rm = TRUE)
andmed$Käive.ii = rowSums(andmed[c("Käive.ii.2020")], na.rm = TRUE) - rowSums(andmed[c("Käive.ii.2019")], na.rm = TRUE)
my.andmed <- andmed %>%
select(Registrikood, Käive.2019, Maksud.2019, Tööjõumaksud.2019, Töötajad.2019, Käive.i, Käive.ii)
# Lae ettevõtete andmed
load("~/Dokumendid/R/EMTA/2020_ii.rdata")
# Lisa Ettevõtete registrist täiendavad koodid
andmed <- left_join(my.andmed, data %>% select(Registrikood, Nimi, Liik, KMKR, EMTAK.kood, EMTAK, Maakond, Linn), by = "Registrikood")
data <- NULL
# lae töötukassa andmed
load("~/Dokumendid/R/Töötukassa/koond.rdata")
koond <- andmed %>%
group_by(EMTAK.kood) %>%
summarise(Töötajad = sum(Töötajad.2019), Maksud = sum(Maksud.2019), Tööjõumaksud = sum(Tööjõumaksud.2019))
hyvitis.koond <- left_join(data.koond, andmed, by = c("Registrikood"))
hyvitis.sum <- hyvitis.koond %>%
group_by(EMTAK.kood) %>%
summarise(Töötajad = sum(Töötajad.2019), Maksud = sum(Maksud.2019), Tööjõumaksud = sum(Tööjõumaksud.2019))
hyvitis.prop = left_join(hyvitis.sum, koond, by = c("EMTAK.kood"), suffix = c("hyvitis", "kokku"))
hyvitis.prop$töötajadpc = hyvitis.prop$Töötajadhyvitis/hyvitis.prop$Töötajadkokku
hyvitis.prop$maksudpc = hyvitis.prop$Maksudhyvitis/hyvitis.prop$Maksudkokku
hyvitis.prop$tööjõumaksudpc = hyvitis.prop$Tööjõumaksudhyvitis/hyvitis.prop$Tööjõumaksudkokku
write.csv(hyvitis.prop, "~/Dokumendid/R/Töötukassa/prop.csv")
|
ab1177543af26d41eda0e29735e1bb4327b51d5f | beb34c320ef5feb6449b81b4cbbba2eebf4b1407 | /individual_scripts_and_data/home_values.R | bdf75b0b896f7365e13ceb81d3b250dacdac9689 | [] | no_license | buczkowskir/POL_251_Spring_2021 | 558cead6b1ee65496b51334f7491293ceaf148b7 | bb9b80255f1d66c4597b7b33ecf333ab657c4b25 | refs/heads/master | 2023-04-09T16:53:31.518910 | 2021-04-23T15:07:07 | 2021-04-23T15:07:07 | 345,797,354 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 2,249 | r | home_values.R |
# Data Analysis of Historic Home Prices
# Ryan Buczkowski
#----------------------------------------------#
# Loading Libraries
pacman::p_load('tidyverse', 'scales')
# Importing Data
read_csv('https://raw.githubusercontent.com/IQSS/workshops/master/R/Rgraphics/dataSets/landdata-states.csv') -> home_values
# Looking at data
summary(home_values)
# Cleaning/summarizing data
home_values %>%
rename('state_abb' = State) %>%
group_by(state_abb) %>%
summarize(housing_mean = mean(Home.Value)) %>%
filter(state_abb != 'DC'
) -> home_values_clean
# Creating state dataset
tibble(state_name = state.name,
state_abb = state.abb,
state_region = state.region) -> states
# Joining data together
inner_join(states, home_values_clean) -> home_values_joined
# Creating CSV file
home_values_joined %>%
write_csv(path = 'home_values.csv')
# Visualizing data
home_values_joined %>%
ggplot(aes(x = reorder(state_abb, housing_mean), y = housing_mean)) +
geom_col(aes(fill = state_region), color = 'black') +
labs(x = 'State',
y = 'Housing Price',
title = 'Mean of Historic Home Price',
subtitle = 'By State',
caption = 'Visualization created using ggplot2 in RStudio \nCreator: Ryan Buczkowski - University of Mississippi - Political Science Department') +
scale_fill_discrete(name = 'State Region') +
theme_minimal() +
scale_y_continuous(labels = dollar) +
theme(
axis.text = element_text(face = 'bold.italic',
size = 9),
axis.title = element_text(face = 'bold',
size = 14),
plot.title = element_text(face = 'bold',
size = 18),
plot.subtitle = element_text(face = 'italic',
size = 9),
legend.position = 'bottom',
legend.background = element_rect(color = 'black'),
legend.title = element_text(face = 'bold'),
legend.text = element_text(face = 'bold.italic'),
plot.caption = element_text(face = 'italic',
size = 9,
hjust = 0)
)
|
38a6906e96607b78410407b45fb9001b619e32ee | 44167d61586c84d4d8290e5e46c1c8a836b45e74 | /analysis/stability_report.R | 947c0d947e83bee27454a5a6752e697228b77451 | [] | no_license | cboettig/bs-tipping | 24027cc993e302667a7bff07bda5251872c6b026 | aae4ded2c2972816a41f6776ab5f991a5592197c | refs/heads/master | 2021-04-15T18:21:44.004715 | 2018-12-18T03:52:43 | 2018-12-18T03:52:43 | 126,869,682 | 1 | 0 | null | null | null | null | UTF-8 | R | false | false | 14,104 | r | stability_report.R | #' ---
#' title: "Stability analysis of a trophic cascade model"
#' author: "Ryan Batt"
#' date: "2018-06-16"
#' abstract: |
#' Makings of a stability analysis of a trophic cascade model. Starting by focusing on fish (adult bass, juvenile bass, and a planktivore), though the model is easily extensible to include phytoplankton and zooplankton for a 5D model.
#' output:
#' html_document:
#' toc: true
#' toc_depth: 4
#' fig_caption: true
#' theme: "readable"
#' template: default
#' pdf_document:
#' toc: true
#' toc_depth: 4
#' template: latex-ryan.template
#' fig_caption: yes
#' geometry: margin=1.0in
#' lineno: true
#' lineSpacing: false
#' titlesec: true
#' documentclass: article
#' placeins: true
#' ---
#+ report-setup, include=FALSE, echo=FALSE, cache=FALSE
# ==========================================
# = Record Time to Get Elapsed Time at End =
# ==========================================
t1 <- Sys.time()
# =================
# = Load Packages =
# =================
library(viridis)
library(phaseR)
library(rootSolve)
library(bs.tipping)
# Report
library(knitr)
library(rmarkdown)
# ================
# = Report Setup =
# ================
doc_type <- c("html", "pdf")[1]
table_type <- c("html"="html", "pdf"="latex")[doc_type]
options("digits"=3) # rounding output to 4 in kable() (non-regression tables)
o_f <- paste(doc_type, "document", sep="_")
# render!
# rmarkdown::render(
# "~/Documents/School&Work/epaPost/bs-tipping/pkgBuild/stability_report.R",
# output_format=o_f,
# output_dir='~/Documents/School&Work/epaPost/bs-tipping/pkgBuild/',
# clean = TRUE
# )
Sys.setenv(PATH=paste0("/Library/TeX/texbin:",Sys.getenv("PATH")))
opts_chunk$set(
fig.path = 'stability_report/',
cache.path='stability_report/',
echo=TRUE,
include=TRUE,
cache=FALSE,
autodep=TRUE,
results='asis',
warning=FALSE,
fig.show="hold",
fig.lp = if(o_f=="html_document"){"**Figure.**"}else{NULL}
)
#' #Setup
#+ setup
qE <- 0.65
qE_end <- 0.1
dt <- 0.01
nYears <- 1000
noise_coeff <- c(0.01, 0.01, 0.01)
#' #Simulation
#+ simulation
# set initial values to equilibrium (roots)
X_init <- pmax(bs.tipping::getRoot(c(A0=1, F0=1, J0=1), pars=c(qE=qE)), 1E-2)
# simulate an example of fish
qE_vec <- seq(qE, qE_end, length.out=nYears/dt)
stateMat <- matrix(NA, nrow=nYears/dt, ncol=3, dimnames=list(NULL, c("A0","F0", "J0")))
stateMat[1,] <- unlist(X_init)
for(j in 2:nrow(stateMat)){ # iterate through time steps
state <- stateMat[j-1,]
dState_dt <- fishStep(X=state, pars=c(qE=(qE_vec[j])))
# Euler Method Approximation
dState <- dState_dt*dt + rnorm(3, sd=c(noise_coeff[1], noise_coeff[2], noise_coeff[3]))*dt
eulerState <- pmax(state + dState, 1E-2)
stateMat[j,] <- eulerState # euler
}
stateMat <- cbind(time=seq(0, nYears-dt, by=dt), qE=qE_vec, stateMat)
#' ##Plot Simulation
#+ plot-simulation, fig.width=3.5, fig.height=6, fig.cap="Simulated time series of adult bass (A0), planktivores (F0), and juvenile bass (J0) over a gradient of harvesting of adult bass (qE)."
par(mfrow=c(3,1), mar=c(2, 2, 0.75, 0.25), ps=8, cex=1, mgp=c(1, 0.25, 0), tcl=-0.15)
plot(stateMat[,c("time","A0")], type='l')
plot(stateMat[,c("time","F0")], type='l')
plot(stateMat[,c("time","J0")], type='l')
#'
#' \FloatBarrier
#'
#' ***
#'
#' #Rearrange equations to represent stability in 1D
#' Start with the equations for the fish dynamics:
#' \begin{array}{llr}
#' \dot{A} &= sJ - qEA - (1-s)A &(1) \\
#' \dot{F} &= d(F_o - F) - c_{FA}FA &(2)\\
#' \dot{J} &= fA - c_{JA}JA - \frac{c_{JF}vJF}{h+v+c_{JF}F} - sJ &(3)
#' \end{array}
#'
#'
#' Then, set $\dot{A}$ and $\dot{J}$ to 0, and solve for $A$ and $J$, respectively:
#' \begin{array}{llr}
#' A&= \frac{sJ}{qE+1-s} &(4)\\[10pt]
#' J&=\frac{fA}{xA+s+\frac{zvF}{h+v+zF}} &(5)\\[10pt]
#' \end{array}
#'
#' Substitute Eq5 into Eq4, and solve for $A$:
#' \begin{array}{llr}
#' A&=\frac{sf}{x(qE+1-s)} - \frac{s}{x} - \frac{zvF}{x(h+v+zF)} &(6)
#' \end{array}
#'
#' Substitute Eq6 into Eq2, giving us the dynamics of $F$ as a function of $F$ and parameters:
#' \begin{array}{llr}
#' \dot{F} &= d(F_o-F) - aF(\frac{sf}{x(qE+1-s)} - \frac{s}{x} - \frac{zvF}{x(h+v+zF)}) &(7)
#' \end{array}
#'
#' Eq7 is what is used in `dF_dt_1state`.
#'
#' **Alternatively**, we can rearrange the equations to perform a different seat of substituions to solve for $\dot{J}$ as a function of $J$ and parameters (juvenile bass):
#' \begin{array}{llr}
#' Q &\equiv 1/(qE + 1 - s) \\
#' \dot{J} &= fsJQ - xsQJ^2 - sJ - \frac{zvJ}{\frac{(h+v)}{(dF_o)(d+asQJ)^{-1}} + z} &(8)
#' \end{array}
#'
#' \FloatBarrier
#'
#' ***
#'
#' #Plots of dState/dt vs State
#' ##dF/dt vs F
#+ plot-dFdt-vs-F, fig.width=3.5, fig.height=3.5, fig.cap="dF/dt vs F. Where the line intersects 0, indicates a value of planktivore abundance that is an equilibrium. Is contingent upon the value of parameters, such as qE. The value of qE used here is the value used for the first time step of the simulation."
# check rate equation ... should be 0 at root
F_grad <- seq(-2, 110, length.out=100)
par(mar=c(2,2,0.75,0.5), mgp=c(1,0.25,0), tcl=-0.15, ps=8, cex=1)
plot(F_grad, dFJ_dt_1state(State0=F_grad, pars=c(qE=qE), stateName="F0"), type='l', ylab="dF/dt", xlab='F')
mtext(paste0('qE = ', round(qE,2)), line=-0.1, adj=0.05, font=2)
abline(h=0, lty=2)
#' This plot of the potential looks wrong to me. At a harvest rate of qE=0.65, F should have an equilibrium near F=100, but this plot shows a quadratic where the change in F is getting more and more positive past ~10. Furthermore, 10 looks like a saddle, not a stable node.
#'
#' ##dJ/dt vs J
#+ plot-dJdt-vs-J, fig.width=3.5, fig.height=3.5, fig.cap="dJ/dt vs J Where the line intersects 0, indicates a value of juvenile bass abundance that is an equilibrium. Is contingent upon the value of parameters, such as qE. The value of qE used here is the value used for the first time step of the simulation."
# check rate equation ... should be 0 at root
J_grad <- seq(0, 850, length.out=1E3)
par(mar=c(2,2,0.75,0.5), mgp=c(1,0.25,0), tcl=-0.15, ps=8, cex=1)
plot(J_grad, dFJ_dt_1state(State0=J_grad, pars=c(qE=qE), stateName="J0"), type='l', ylab="dJ/dt", xlab='J')
mtext(paste0('qE = ', round(qE,2)), line=-0.1, adj=0.05, font=2)
abline(h=0, lty=2)
#' ##dJ/dt vs J for various qE
#+ plot-dJdt-vs-J-qE, fig.width=3.5, fig.height=3.5, fig.cap="dJ/dt vs J Where the line intersects 0, indicates a value of juvenile bass abundance that is an equilibrium. Is contingent upon the value of parameters, such as qE. Thus, the dJ/dt vs J curve is plotted for several values of qE, providing a visualization of how the stability landscape changes with harvest rate."
# check rate equation ... should be 0 at root
J_grad <- seq(-1, 850, length.out=1E3)
# qE_vals <- seq(qE, qE_end, length.out=4)
qE_vals <- seq(1.25, 0.25, length.out=8)
dFJ_dt_1state_Jwrap <- function(X){dFJ_dt_1state(State0=J_grad, pars=c(qE=X), stateName="J0")}
dJ_dt_qE <- lapply(qE_vals, FUN=dFJ_dt_1state_Jwrap)
names(dJ_dt_qE) <- paste0("qE",round(qE_vals,2))
par(mar=c(2,2,0.75,0.5), mgp=c(1,0.25,0), tcl=-0.15, ps=8, cex=1)
ylim <- range(dJ_dt_qE)
cols <- viridis(n=length(qE_vals))
plot(J_grad, dJ_dt_qE[[1]], type='l', ylab="dJ/dt", xlab='J', ylim=ylim, col=cols[1])
for(j in 2:length(qE_vals)){
lines(J_grad, dJ_dt_qE[[j]], col=cols[j])
}
legend('bottomleft', lty=1, col=cols, legend=paste0("qE = ",round(qE_vals,2)), ncol=2, y.intersp=0.6, x.intersp=0.5)
abline(h=0, lty=2)
#'
#'
#' \FloatBarrier
#'
#' ***
#'
#' #Sanity Check on dF/dt
#' ##Part 1
#' The code below is taken from the examples in the help file for `dF_dt_1state`.
#'
#+ sanity-check1, results='markup'
getRoot(c(A0=1000, F0=1, J0=1000), pars=c(qE=0.5)) # find equilibria when bass are abundant
dFJ_dt_1state(State0=0.06712064, pars=c(qE=0.5), stateName="F0") # F0 set to equilibrium when bass start as abundant
#' Check -- results make sense, the `getRoot` function finds that when bass start off super abundant, planktivores should stabilize near `0`. Using the `dF_dt_1state` function, we find that the change in planktivore abundance per unit time is very near `0` when planktivore abundance is near `0`. Great.
#'
#' ##Part 2
#+ sanity-check2, results='markup'
getRoot(c(A0=1, F0=1, J0=1), pars=c(qE=0.5)) # find equilibria when bass are rare
dFJ_dt_1state(State0=17.890184, pars=c(qE=0.5), stateName='F0') # F0 set to equilibrium when bass start as rare
#' Check -- again, we find that according to `dF_dt_1state`, $dF/dt$ is near `0` when fish abundance is set near to equilibrium. This time the equilibrium value for planktivores was higher because the bass starting point was low. Right. Great.
#'
#' ##Part 3
#+ sanity-check3, results='markup'
getRoot(c(A0=1000, F0=1, J0=1000), pars=c(qE=0.65)) # find equilibria when bass are abundant
dFJ_dt_1state(State0=0.09136212, pars=c(qE=0.65), stateName="F0") # check planktivore equation for rate of change
fishStep(X=c(A0=364.51517642, F0=0.09136212, J0=838.38490576)) # re-examine rates of change of fish near equilibrium
#' Here we are repeating **Part 1**, but we've increased `qE` from `0.5` to `0.65`. I'm also cross-checking the dF/dt values from `dF_dt_1state` with those reported by `fishStep`, which is what `getRoot` uses to find equilibria. With the slightly higher harvest and high starting values for bass, we again find that planktivores should stabilize near `0`, and both `dF_dt_1state` and `fishStep` indicate that dF/dt is very small when setting F to this near-`0` equilibrium value. It's a little annoying that these two functions don't report the *exact* same value for dF/dt, but in general, this seems to check out. So far, things make sense.
#'
#' ##Part 4
#+ sanity-check4, results='markup'
getRoot(c(A0=1, F0=1, J0=1), pars=c(qE=0.65)) # find equilibria when bass are rare
dFJ_dt_1state(State0=100, pars=c(qE=0.65), stateName="F0") # F0 set to equilibrium when bass start as rare # WTF?!
fishStep(X=c(A0=6.275129e-18, F0=100, J0=1.443280e-17)) # but this one says that dF/dt should be ~0!!
#' Here we again use the `qE=0.65` harvest rate, with low starting values for bass. But instead of `dF_dt_1state` reporting a near-`0` value for the rate of change in planktivores, it's reporting a very large positive value. This last example is what is making me scratch my head.
#'
#' Update: apparently **Part 4** (above) doesn't work properly because in the algebra we dvide by A in a place that implies the assumption that A≠0. So when we try to use the equation when A=0, it doesn't work well.
#'
#'
#'
#' \FloatBarrier
#'
#' ***
#'
#' #Stability Analysis
#' ##Critical Values
#+ critVals
(critVals <- findCritHarv()) # 0.24 and 1.22
#' These critical values were found numerically using the 1D model.
#'
#' ##Stability Classification
#+ stabClass, results="markup"
qEvec <- c(0, critVals[1]-0.2, critVals[1], critVals[2]-0.1, critVals[2]-0.05, critVals[2])
lout <- lapply(qEvec, stabClass)
do.call(rbind, lout)
#' I'm a little confused, because there is no place I could find with 2 stable nodes and 1 saddle point.
#'
#' ##Phase Portrait
#+ figure-phasePortrait, fig.width=6, fig.height=6, fig.cap="**Figure 1.** A phase portrait of the system for varying values of harvest (qE). The vector field (indicating the direction and speed that the system moves through phase space at that point) is represented by gray arrows. Nullclines are represented red and blue lines, indicating where dJ/dt and dF/dt are equal to zero, respectively. Trajectories starting at arbitrary initial points (open diamonds) and continuing the along the accompanying solid black line indicate how the system moves from the initial point through phase space for 20 years. Equilibria are indicated by points: solid filled circle is a stable node, an 'X' is a saddle point. An equilibrium occurs whereever the nullclines cross. The different panels correspond to different values of harvest (qE). "
qEvals <- rev(c(critVals[1]-0.2, critVals[1], critVals[2]-0.1, critVals[2]))
par(mfrow=c(2,2), mar=c(2,2,1,0.5), mgp=c(1,0.25,0), tcl=-0.15, cex=1, ps=9, cex.axis=0.85)
for(j in 1:4){
(bs.tipping::phasePortrait(qE=qEvals[j], pars=NULL, nFlow=10, nNull=300, t.end=20, addLeg=TRUE))
mtext(paste0("qE = ",round(qEvals[j],2)), side=3, line=0, adj=0, font=2)
}
#'
#' \FloatBarrier
#'
#' ***
#'
#'
#' ##Growth and Consumption Curves: dJ/dt vs J
#+ figure-grow-cons-J, fig.width=6, fig.height=6, fig.cap="**Figure.** Growth and consumption curves for juvenile bass (J). Different panels show the curves for varying values of harvest rate on adult bass (qE)."
# dFJ_dt_1state <- function(State0, pars, stateName=c("J0","F0"), parts=FALSE){
plot_growCons <- function(stateRange=c(0,999), pars=c(qE=1.0), stateName=c("J0","F0"), nGrid=100){
stateName <- match.arg(stateName)
stopifnot(length(stateRange)==2)
names(stateRange) <- c("from", "to")
grid_args <- c(as.list(stateRange), length.out=nGrid)
stateGrid <- do.call(seq, grid_args)
rates <- t(sapply(stateGrid, dFJ_dt_1state, pars=pars, stateName=stateName, parts=TRUE))
state_rates <- data.table(state=stateGrid, rates)
ylim <- state_rates[,range(c(growth, consumption))] #range(state_rates[,c("growth", "consumption")])
state_rates[,plot(state,growth, col='blue', type='l', ylim=ylim, xlab="", ylab="")]
state_rates[,lines(state,consumption, col='red')]
}
qEvals <- rev(c(critVals[1]-0.2, critVals[1], critVals[2]-0.1, critVals[2]))
par(mfrow=c(2,2), mar=c(2,2,1,0.5), mgp=c(1,0.25,0), tcl=-0.15, cex=1, ps=9, cex.axis=0.85)
for(j in 1:4){
plot_growCons(pars=c(qE=qEvals[j]))
mtext(paste0("qE = ",round(qEvals[j],2)), side=3, line=0, adj=0, font=2)
mtext("dJ/dt", side=2, line=0.85)
mtext("J", side=1, line=0.85)
legend("topleft", legend=c("growth", "consumption"), col=c("blue","red"), lty=1)
}
#' \FloatBarrier
#'
#' ***
#'
#' #Session Info
#+ sessionInfo, results='markup'
difftime(Sys.time(), t1) # how long it took to run these models/ produce this report
Sys.time()
sessionInfo()
|
204f7bb71f9af2b112743a4c8efb43f5835d4e8c | 036cc8379ad8795ea1489960503e92a68017b322 | /man/aug.scanone.Rd | 72378ac98c1fcacb47aee40626eae0e9532535bc | [] | no_license | kbroman/qtlview | c189ee1425855afc5af4a03077e9e0a65f654fa9 | beaf6198de1e9e689f1e1e808113641166908624 | refs/heads/master | 2021-12-01T20:38:50.546974 | 2013-06-28T14:56:35 | 2013-06-28T14:56:35 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 2,168 | rd | aug.scanone.Rd | \name{aug.scanone}
\alias{aug.scanone}
\alias{plot.aug.scanone}
\alias{summary.aug.scanone}
\alias{plot.summary.aug.scanone}
\alias{plot.summary.aug.scanone}
\title{Plot 1-D scan of LOD and/or means}
\description{
Profiles of one or more phenotypes. If only one phenotype, in
addition profile the means by genotype.
}
\usage{
aug.scanone(traitnames = mytrait(),
cross = B6BTBR07,
sex = sexes,
method = "ehk",
log10 = rep(FALSE, length(traitnames)),
log.offset = 1,
lod.error = 100,
category = B6BTBR07.source,
...)
\method{plot}{aug.scanone}(x, chr = levels(x$chr), traitnames = names(x)[-(1:2)],
col.scheme = c("redblue", "cm", "gray", "heat", "terrain", "topo"),
gamma = 0.6, allow.neg = FALSE, max.names = 50, zscale = TRUE,
main = "", threshold.level = 0.05, max.lod = 20, category = NULL, \dots)
\method{summary}{aug.scanone}(object, chr = levels(object$chr),
threshold.level = 0.05, mean.peaks = FALSE, category = NULL, \dots)
\method{print}{summary.aug.scanone}(x, digits = 2, \dots)
\method{plot}{summary.aug.scanone}(x, chr = dimnames(x$lod)[[2]],
threshold.level = 0.05, max.lod = 20, max.names = 100,
by = c("chr","trait","phenotype"), scale = c("cM","Mb"),
cex = 2, pch = 3, \dots)
}
\details{
\code{aug.scanone} creates multiple scanone's using
\code{\link[qtl]{scanone}}. The plot uses ideas from
\code{\link[qtl]{plot.scantwo}}. The \code{summary} method produces a
large list, which can itself be plotted.
}
\seealso{\code{\link{myplot}}}
\examples{
multtrait.plot(cross.name="B6BTBR07",
category="rbm", ## Later this will allow for tissues, modules.
traitnames=mytrait(c("il.18","mpo")),
chr=c(1:19,"X"),
col.scheme=c("redblue", "cm", "gray", "heat", "terrain",
"topo"),
threshold.level=0.05, ## Drop traits that have max below threshold.
max.names=100, ## Include names if number of traits < max.names.
max.lod = 20) ## Truncate lod at max.lod for color scheme.
}
\keyword{ ~kwd1 }
|
9e7ccb1c7008faf9cab71e551330002b56ae43c3 | b2f61fde194bfcb362b2266da124138efd27d867 | /code/dcnf-ankit-optimized/Results/QBFLIB-2018/A1/Database/Pan/k_branch_n/k_branch_n-4/k_branch_n-4.R | fb128d5990897441d198a208de019d92566c4ed8 | [] | no_license | arey0pushpa/dcnf-autarky | e95fddba85c035e8b229f5fe9ac540b692a4d5c0 | a6c9a52236af11d7f7e165a4b25b32c538da1c98 | refs/heads/master | 2021-06-09T00:56:32.937250 | 2021-02-19T15:15:23 | 2021-02-19T15:15:23 | 136,440,042 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 62 | r | k_branch_n-4.R | 45371ddd55ee93a13a055f8155de99aa k_branch_n-4.qdimacs 803 2565 |
f3323ce419e6dc008cde18aaa37510e89064eac4 | f9dbed5e13b8020ff385e5ffd3ed52c640d5d936 | /2.Training/1.Iterator.R | 21f6f943f01f63ee5dab68279dd58aae59418947 | [] | no_license | ji9su/OA_Net | d2dbd05de8d175c317acbafb03b9129f108d297b | 6261d4b050dfde4e1b22cc8b603e9f52f157227d | refs/heads/main | 2023-01-19T14:55:44.495085 | 2020-11-23T11:15:13 | 2020-11-23T11:15:13 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 5,374 | r | 1.Iterator.R |
# Libraries
library(OpenImageR)
library(abind)
library(jpeg)
library(mxnet)
img_info_path <- 'img_info.RData'
load(img_info_path)
OA_data <- read.csv("data/label.csv")
train_table <- OA_data[OA_data[,'group'] == 1, (-2)]
val_table <- OA_data[OA_data[,'group'] == 2, (-2)]
#test_table <- OA_data[OA_data[,'group'] == 3, (-2)]
label_table <- OA_data[, (-2)]
train_table <- train_table[, c(1:7)]
my_iterator_core <- function (batch_size = 6, sample_type = 'train', aug_flip = TRUE,
aug_rotate = TRUE, aug_crop = TRUE, oversampling = FALSE) {
batch <- 0
if (sample_type == 'train') {
sample_ids <- train_table[,'names']
sample_label <- train_table
} else if (sample_type == 'val') {
sample_ids <- val_table[,'names']
sample_label <- val_table
} else {
sample_ids <- label_table[,'names']
sample_label <- label_table
}
batch_per_epoch <- floor(length(sample_ids)/batch_size)
reset <- function() {batch <<- 0}
iter.next <- function() {
batch <<- batch + 1
if (batch > batch_per_epoch) {return(FALSE)} else {return(TRUE)}
}
value <- function() {
if (oversampling == TRUE) {
idx_1 = sample(which(sample_label[sample_label[,1] %in% sample_ids, 2] == 1), batch_size/6, replace = TRUE)
idx_2 = sample(which(sample_label[sample_label[,1] %in% sample_ids, 3] == 1), batch_size/6, replace = TRUE)
idx_3 = sample(which(sample_label[sample_label[,1] %in% sample_ids, 4] == 1), batch_size/6, replace = TRUE)
idx_4 = sample(which(sample_label[sample_label[,1] %in% sample_ids, 5] == 1), batch_size/6, replace = TRUE)
idx_5 = sample(which(sample_label[sample_label[,1] %in% sample_ids, 6] == 1), batch_size/6, replace = TRUE)
idx_6 = sample(which(sample_label[sample_label[,1] %in% sample_ids, 7] == 1), batch_size/6, replace = TRUE)
idx = c(idx_1, idx_2, idx_3, idx_4, idx_5, idx_6)
#idx = c(idx_1, idx_2)
idx <- sort(idx)
} else {
idx <- 1:batch_size + (batch - 1) * batch_size
idx[idx > length(sample_ids)] <- sample(1:(idx[1]-1), sum(idx > length(sample_ids)))
idx <- sort(idx)
}
img_array_list <- list()
for (i in 1:batch_size) {
#print(sample_ids[idx[i]])
img_array_list[[i]] <- readJPEG(img_list[[sample_ids[idx[i]]]])
}
img_array <- abind(img_array_list, along = 4)
if (aug_flip) {
if (sample(c(TRUE, FALSE), 1)) {
img_array <- img_array[,dim(img_array)[2]:1,,,drop = FALSE]
}
}
if (aug_rotate) {
for (i in 1:batch_size) {
ROTATE_ANGLE <- sample(c(0:15, 345:359), 1)
img_array[,,,i] <- rotateImage(img_array[,,,i], ROTATE_ANGLE)
}
}
if (aug_crop) {
random.row <- sample(0:40, 1)
random.col <- sample(0:40, 1)
img_array <- img_array[random.row+1:(800-40),random.col+1:(800-40),,,drop = FALSE]
}
label <- array(0, dim =c(6, batch_size))
for(i in 1:batch_size) {
label[,i] <- t(t(as.numeric(sample_label[sample_label[,1] == sample_ids[idx[i]], 2:7])))
#label[,i] <- t(t(as.numeric(sample_label[sample_label[,1] == sample_ids[idx[i]], 2])))
}
data = mx.nd.array(img_array)
label = mx.nd.array(label)
return(list(data = data, label = label))
}
return(list(reset = reset, iter.next = iter.next, value = value, batch_size = batch_size, batch = batch, sample_ids = sample_ids))
}
my_iterator_func <- setRefClass("Custom_Iter",
fields = c("iter", "batch_size", "sample_type", "img_list", "select_sample", 'aug_flip', 'aug_crop', 'aug_rotate', 'oversampling'),
contains = "Rcpp_MXArrayDataIter",
methods = list(
initialize = function(iter, batch_size = 12, sample_type = 'train', aug_flip = TRUE, aug_crop = TRUE, aug_rotate = TRUE, oversampling = TRUE) {
.self$iter <- my_iterator_core(batch_size = batch_size, sample_type = sample_type,
aug_flip = aug_flip, aug_crop = aug_crop, aug_rotate = aug_rotate, oversampling = oversampling)
.self
},
value = function(){
.self$iter$value()
},
iter.next = function(){
.self$iter$iter.next()
},
reset = function(){
.self$iter$reset()
},
finalize=function(){
}
)
)
# Test iterator function
# You can delete symbol # for running the test
#my_iter <- my_iterator_func(iter = NULL, batch_size = 12, sample_type = 'train', aug_flip = TRUE,
# aug_crop = FALSE, aug_rotate = TRUE, oversampling = TRUE)
#my_iter$reset()
#t0 <- Sys.time()
#my_iter$iter.next()
#test <- my_iter$value()
|
7c31702d625b24d455da6374ba730e91ca186b54 | 8aeaed41d216fb2323f21b4d236d079d83322eeb | /Project1/Plot4.R | e1fe45899a32e562ac531cf2216a2384933d7c37 | [] | no_license | muammara/JHExploratoryDataAnalysis | a0b915ff1608176c16d6ecc07c97d7efd9f36d83 | 41bb9a83ce247e2f9dc5e8c79485ab7f48388420 | refs/heads/master | 2021-01-19T14:12:41.245380 | 2017-04-13T06:40:42 | 2017-04-13T06:40:42 | 88,132,429 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,200 | r | Plot4.R | par(bg="white",mar=c(4,4,2,2),mfrow=c(2,2))
cols=c("character","character",rep("numeric",7))
frm<-read.table(file="e:/ds/EXP/household_power_consumption.txt",sep=";",header=T,stringsAsFactors=F,colClasses=cols,na.strings="?")
frm2<-frm[frm$Date == "1/2/2007" | frm$Date == "2/2/2007",]
frm2$DateTime<-strptime(paste(frm2$Date,frm2$Time),"%d/%m/%Y %H:%M:%S")
png(file="e:/ds/EXP/plot4.png",width=480,height=480,units="px",type="cairo")
par(bg="white",mar=c(4,4,2,2),mfrow=c(2,2))
plot(frm2$DateTime, as.numeric(frm2$Global_active_power),type="l",xlab="",ylab="Global Active Power (kilowatts)")
plot(frm2$DateTime, as.numeric(frm2$Voltage),type="l",xlab="datetime",ylab="Voltage")
with(frm2, plot(DateTime,as.numeric(Sub_metering_1), type="n",xlab="",ylab="Energy sub metering"))
points(frm2$DateTime, frm2$Sub_metering_1, type="l")
points(frm2$DateTime, frm2$Sub_metering_2, type="l",col="red")
points(frm2$DateTime, frm2$Sub_metering_3, type="l",col="blue")
legend("topright",lwd=1,legend =c("Sub_metering_1","Sub_metering_2","Sub_metering_3"),col=c("black","blue","red"))
plot(frm2$DateTime, as.numeric(frm2$Global_reactive_power),type="l",ylab="Globale_reactive_power",xlab="datetime")
dev.off()
|
c460930747d21444c3013aa75ba86441c3b162e7 | 7eb63399fa00e3c547e5933ffa4f47de515fe2c6 | /man/lgcpSimSpatial.Rd | 0a2569ce611b3c9a0418ca96f13e05674beca6f8 | [] | no_license | bentaylor1/lgcp | a5cda731f413fb30e1c40de1b3360be3a6a53f19 | 2343d88e5d25ecacd6dbe5d6fcc8ace9cae7b136 | refs/heads/master | 2021-01-10T14:11:38.067639 | 2015-11-19T13:22:19 | 2015-11-19T13:22:19 | 45,768,716 | 2 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,531 | rd | lgcpSimSpatial.Rd | % Generated by roxygen2 (4.1.1): do not edit by hand
% Please edit documentation in R/spatialOnly.R
\name{lgcpSimSpatial}
\alias{lgcpSimSpatial}
\title{lgcpSimSpatial function}
\usage{
lgcpSimSpatial(owin = NULL, spatial.intensity = NULL,
expectednumcases = 100, cellwidth = 0.05,
model.parameters = lgcppars(sigma = 2, phi = 0.2),
spatial.covmodel = "exponential", covpars = c(), ext = 2,
plot = FALSE, inclusion = "touching")
}
\arguments{
\item{owin}{observation window}
\item{spatial.intensity}{an object that can be coerced to one of class spatialAtRisk}
\item{expectednumcases}{the expected number of cases}
\item{cellwidth}{width of cells in same units as observation window}
\item{model.parameters}{parameters of model, see ?lgcppars. Only set sigma and phi for spatial model.}
\item{spatial.covmodel}{spatial covariance function, default is exponential, see ?CovarianceFct}
\item{covpars}{vector of additional parameters for spatial covariance function, in order they appear in chosen model in ?CovarianceFct}
\item{ext}{how much to extend the parameter space by. Default is 2.}
\item{plot}{logical, whether to plot the latent field.}
\item{inclusion}{criterion for cells being included into observation window. Either 'touching' or 'centroid'. The former includes all cells that touch the observation window, the latter includes all cells whose centroids are inside the observation window.}
}
\value{
a ppp object containing the data
}
\description{
A function to simulate from a log gaussian process
}
|
e28e26947377aad205d2e2876fd2333f9749eab8 | 29585dff702209dd446c0ab52ceea046c58e384e | /RJafroc/inst/GUI/server.R | 58fb3fee799d4ce3f999a2d072b894f299f50343 | [] | no_license | ingted/R-Examples | 825440ce468ce608c4d73e2af4c0a0213b81c0fe | d0917dbaf698cb8bc0789db0c3ab07453016eab9 | refs/heads/master | 2020-04-14T12:29:22.336088 | 2016-07-21T14:01:14 | 2016-07-21T14:01:14 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 67,754 | r | server.R | ReportTextForGUI <- function(dataset, method = "DBMH", fom = "wJAFROC", alpha = 0.05, covEstMethod = "Jackknife", nBoots = 200) {
UNINITIALIZED <- -Inf
if (method == "DBMH") {
methodTxt <- "DBM-MRMC HILLIS SIGNIFICANCE TESTING"
result <- DBMHAnalysis(dataset, fom, alpha)
} else if (method == "ORH") {
methodTxt <- "OBUCHOWSKI-ROCKETTE-HILLIS SIGNIFICANCE TESTING"
result <- ORHAnalysis(dataset, fom, alpha, covEstMethod, nBoots)
}
ciPercent <- 100 * (1 - alpha)
reportTxt <- paste0("RJafroc SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ",
"IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ",
"FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ",
"AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ",
"LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ",
"OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS ",
"IN THE SOFTWARE.\n================================================================================\n")
reportTxt <- paste(reportTxt, sprintf(paste("Package build stats:", packageDescription("RJafroc", fields = "Built"))), sep = "\n")
dateTime <- paste0("Run date: ", base::format(Sys.time(), "%b %d %Y %a %X %Z"))
reportTxt <- paste(reportTxt, sprintf(dateTime), sep = "\n")
reportTxt <- paste(reportTxt, sprintf(" FOM selected : %s", fom), sep = "\n")
reportTxt <- paste(reportTxt, sprintf("================================================================================\n"), sep = "\n")
NL <- dataset$NL
LL <- dataset$LL
lesionNum <- dataset$lesionNum
lesionID <- dataset$lesionID
lesionWeight <- dataset$lesionWeight
maxNL <- dim(NL)[4]
dataType <- dataset$dataType
modalityID <- dataset$modalityID
readerID <- dataset$readerID
I <- length(modalityID)
J <- length(readerID)
K <- dim(NL)[3]
K2 <- dim(LL)[3]
K1 <- K - K2
nLesionPerCase <- rowSums(lesionID != UNINITIALIZED)
reportTxt <- paste(reportTxt, sprintf(" Significance testing method: %s", methodTxt), sep = "\n")
reportTxt <- paste(reportTxt, sprintf(" Number of Readers : %d", J), sep = "\n")
reportTxt <- paste(reportTxt, sprintf(" Number of Treatments : %d", I), sep = "\n")
reportTxt <- paste(reportTxt, sprintf(" Number of Normal Cases : %d", K1), sep = "\n")
reportTxt <- paste(reportTxt, sprintf(" Number of Abnormal Cases : %d", K2), sep = "\n")
reportTxt <- paste(reportTxt, sprintf(" Fraction of Normal Cases : %f", K1/K), sep = "\n")
if (dataType == "FROC") {
reportTxt <- paste(reportTxt, sprintf(" Min number of lesions per diseased case : %d", min(nLesionPerCase)), sep = "\n")
reportTxt <- paste(reportTxt, sprintf(" Max number of lesions per diseased case : %d", max(nLesionPerCase)), sep = "\n")
reportTxt <- paste(reportTxt, sprintf(" Mean number of lesions per diseased case : %f", mean(nLesionPerCase)), sep = "\n")
reportTxt <- paste(reportTxt, sprintf(" Total number of lesions : %d", sum(nLesionPerCase)), sep = "\n")
nl <- NL[, , (K1 + 1):K, ]
dim(nl) <- c(I, J, K2, maxNL)
maxNLRating <- apply(nl, c(1, 2, 3), max)
maxLLRating <- apply(LL, c(1, 2, 3), max)
maxNLRating[which(maxNLRating == UNINITIALIZED)] <- -2000
maxLLRating[which(maxLLRating == UNINITIALIZED)] <- -2000
ILF <- sum(maxNLRating > maxLLRating) + 0.5 * sum(maxNLRating == maxLLRating)
ILF <- ILF/I/J/K2
reportTxt <- paste(reportTxt, sprintf(" Inc. Loc. Frac. : %f\n\n", ILF), sep = "\n")
reportTxt <- paste(reportTxt, sprintf("================================================================================\n"), sep = "\n")
reportTxt <- paste(reportTxt, sprintf(" Avg. number of non-lesion localization marks per reader on non-diseased cases: %f", sum(NL[, , 1:K1, ] != UNINITIALIZED)/(I * J * K1)), sep = "\n")
reportTxt <- paste(reportTxt, sprintf(" Avg. number of non-lesion localization marks per reader on diseased cases: %f", sum(NL[, , (K1 + 1):K, ] != UNINITIALIZED)/(I * J * K2)), sep = "\n")
reportTxt <- paste(reportTxt, sprintf(" Avg. number of lesion localization marks per reader : %f\n", sum(LL != UNINITIALIZED)/(I * J * K2)), sep = "\n")
}
reportTxt <- paste(reportTxt, paste("================================================================================\n",
" ====================================================================",
" ***** Overview *****",
" ====================================================================",
" Three analyses are presented: ",
" (1) Analysis 1 treats both readers and cases as random samples",
" --results apply to the reader and case populations;",
" (2) Analysis 2 treats only cases as a random sample",
" --results apply to the population of cases but only for the",
" readers used in this study; and",
" (3) Analysis 3 treats only readers as a random sample",
" --results apply to the population of readers but only for the",
" cases used in this study.\n",
" For all three analyses, the null hypothesis of equal treatments is",
sprintf(" tested in part (a), treatment difference %d%% confidence intervals", ciPercent), sprintf(" are given in part (b), and treatment %d%% confidence intervals are", ciPercent), " given in part (c). Parts (a) and (b) are based on the treatment x", " reader x case ANOVA while part (c) is based on the reader x case",
" ANOVA for the specified treatment; these ANOVA tables are displayed",
" before the analyses. Different error terms are used as indicated",
" for parts (a), (b), and (c) according to whether readers and cases",
" are treated as fixed or random factors. Note that the treatment",
" confidence intervals in part (c) are based only on the data for the",
" specified treatment, rather than the pooled data. Treatment",
sprintf(" difference %d%% confidence intervals for each reader are presented", ciPercent),
" in part (d) of Analysis 2; each interval is based on the treatment",
" x case ANOVA table (not included) for the specified reader.\n", sep = "\n"),
sep = "\n")
reportTxt <- paste(reportTxt, paste(" ===========================================================================",
" ***** Estimates *****",
" ===========================================================================\n",
" TREATMENT", sep = "\n"), sep = "\n")
string <- " "
for (i in 1:I) {
string <- paste0(string, "----------")
if (i < I) {
string <- paste0(string, "---")
}
}
reportTxt <- paste(reportTxt, string, sep = "\n")
string <- " READER "
for (i in 1:I) {
string <- paste0(string, sprintf("%-10.10s", dataset$modalityID[i]))
if (i < I) {
string <- paste0(string, " ")
}
}
reportTxt <- paste(reportTxt, string, sep = "\n")
string <- "---------- "
for (i in 1:I) {
string <- paste0(string, "----------")
if (i < I) {
string <- paste0(string, " ")
}
}
reportTxt <- paste(reportTxt, string, sep = "\n")
for (j in 1:J) {
string <- sprintf("%-10.10s ", dataset$readerID[j])
for (i in 1:I) {
string <- paste0(string, sprintf("%10.8f", result$fomArray[i, j]))
if (i < I) {
string <- paste0(string, " ")
}
}
reportTxt <- paste(reportTxt, string, sep = "\n")
}
reportTxt <- paste(reportTxt, "\n", sep = "\n")
reportTxt <- paste(reportTxt, " TREATMENT MEANS (averaged across readers)", "---------- -----------------------------", sep = "\n")
for (i in 1:I) {
string <- paste0(sprintf("%-10.10s %10.8f", dataset$modalityID[i], mean(result$fomArray[i, ])))
reportTxt <- paste(reportTxt, string, sep = "\n")
}
reportTxt <- paste(reportTxt, "\n\n", sep = "\n")
reportTxt <- paste(reportTxt, " TREATMENT MEAN DIFFERENCES", "---------- ---------- -----------", sep = "\n")
for (i in 1:I) {
if (i < I) {
for (ip in (i + 1):I) {
reportTxt <- paste(reportTxt, sprintf("%-10.10s - %-10.10s %10.8f", dataset$modalityID[i], dataset$modalityID[ip], mean(result$fomArray[i, ]) - mean(result$fomArray[ip, ])), sep = "\n")
}
}
}
reportTxt <- paste(reportTxt, "\n\n\n", sep = "\n")
if (method == "DBMH") {
if (J > 1) {
reportTxt <- paste(reportTxt,
" ===========================================================================",
" ***** ANOVA Tables *****",
" ===========================================================================\n",
" TREATMENT X READER X CASE ANOVA\n",
"Source SS DF MS ",
"------ -------------------- ------ ------------------", sep = "\n")
for (l in 1:7) {
reportTxt <- paste(reportTxt, sprintf(" %5s %20.8f %6d %18.8f", result$anovaY[l, 1], result$anovaY[l, 2], result$anovaY[l, 3], result$anovaY[l, 4]), sep = "\n")
}
reportTxt <- paste(reportTxt, sprintf(" %5s %20.8f %6d", result$anovaY[8, 1], result$anovaY[8, 2], result$anovaY[8, 3]), sep = "\n")
reportTxt <- paste(reportTxt, "\n\n", sep = "\n")
reportTxt <- paste(reportTxt, " TREATMENT X READER X CASE ANOVA", sep = "\n")
reportTxt <- paste(reportTxt, "\n\n", sep = "\n")
reportTxt <- paste(reportTxt, " Mean Squares", sep = "\n")
string <- " Source df "
for (i in 1:I) {
string <- paste0(string, sprintf("%-10.10s", dataset$modalityID[i]))
if (i < I) {
string <- paste0(string, " ")
}
}
reportTxt <- paste(reportTxt, string, sep = "\n")
string <- " ------ --- "
for (i in 1:I) {
string <- paste0(string, "---------- ")
}
reportTxt <- paste(reportTxt, string, sep = "\n")
for (l in 1:3) {
string <- sprintf(" %2s %6d ", result$anovaYi[l, 1], result$anovaYi[l, 2])
for (i in 1:I) {
string <- paste0(string, sprintf("%10.8f", result$anovaYi[l, i + 2]))
if (i < I) {
string <- paste0(string, " ")
}
}
reportTxt <- paste(reportTxt, string, sep = "\n")
}
}
reportTxt <- paste(reportTxt,
" ===========================================================================",
" ***** Variance Components Estimates *****",
" ===========================================================================\n",
" DBM variance component and covariance estimates\n",
" DBM Component Estimate ",
" ----------------------- ----------------",
sprintf(" Var(R) %16.8f", result$varComp$varComp[1]),
sprintf(" Var(C) %16.8f", result$varComp$varComp[2]),
sprintf(" Var(T*R) %16.8f", result$varComp$varComp[3]),
sprintf(" Var(T*C) %16.8f", result$varComp$varComp[4]),
sprintf(" Var(R*C) %16.8f", result$varComp$varComp[5]),
sprintf(" Var(Error) %16.8f", result$varComp$varComp[6]), sep = "\n")
} else {
reportTxt <- paste(reportTxt,
" ===========================================================================",
" ***** Variance Components Estimates *****",
" ===========================================================================\n",
" Obuchowski-Rockette variance component and covariance estimates\n",
" OR Component Estimate ",
" ----------------------- ----------------",
sprintf(" Var(R) %16.8f", result$varComp$varCov[1]),
sprintf(" Var(T*R) %16.8f", result$varComp$varCov[2]),
sprintf(" COV1 %16.8f", result$varComp$varCov[3]),
sprintf(" COV2 %16.8f", result$varComp$varCov[4]),
sprintf(" COV3 %16.8f", result$varComp$varCov[5]),
sprintf(" Var(Error) %16.8f", result$varComp$varCov[6]), sep = "\n")
}
smallestDispalyedPval <- 1e-04
reportTxt <- paste(reportTxt, "\n", sep = "\n")
if (J > 1) {
reportTxt <- paste(reportTxt,
" ===========================================================================",
" ***** Analysis 1: Random Readers and Random Cases *****",
" ===========================================================================\n\n",
" (Results apply to the population of readers and cases)\n\n", sep = "\n")
reportTxt <- paste(reportTxt, sprintf(" a) Test for H0: Treatments have the same %s figure of merit.\n\n", fom), sep = "\n")
reportTxt <- paste(reportTxt,
" Source DF Mean Square F value Pr > F ",
" ---------- ------ --------------- ------- -------", sep = "\n")
if (method == "DBMH") {
if (result$pRRRC >= smallestDispalyedPval) {
reportTxt <- paste(reportTxt, sprintf(" Treatment %6d %15.8f %7.2f %7.4f", I - 1, result$anovaY[1, 4], result$fRRRC, result$pRRRC), sep = "\n")
} else {
reportTxt <- paste(reportTxt, sprintf(" Treatment %6d %15.8f %7.2f <%6.4f", I - 1, result$anovaY[1, 4], result$fRRRC, smallestDispalyedPval), sep = "\n")
}
reportTxt <- paste(reportTxt, sprintf(" Error %6.2f %15.8f", result$ddfRRRC, result$anovaY[4, 4] + max(result$anovaY[5, 4] - result$anovaY[7, 4])), sep = "\n")
reportTxt <- paste(reportTxt, " Error term: MS(TR) + max[MS(TC) - MS(TRC), 0]\n", sep = "\n")
} else {
if (result$pRRRC >= smallestDispalyedPval) {
reportTxt <- paste(reportTxt, sprintf(" Treatment %6d %15.8f %7.2f %7.4f", I - 1, result$msT, result$fRRRC, result$pRRRC), sep = "\n")
} else {
reportTxt <- paste(reportTxt, sprintf(" Treatment %6d %15.8f %7.2f <%6.4f", I - 1, result$msT, result$fRRRC, smallestDispalyedPval), sep = "\n")
}
reportTxt <- paste(reportTxt, sprintf(" Error %6.2f %15.8f", result$ddfRRRC, result$msTR + max(J * (result$varComp[3, 2] - result$varComp[4, 2]), 0)), sep = "\n")
reportTxt <- paste(reportTxt, " Error term: MS(TR) + J * max[Cov2 - Cov3, 0]\n", sep = "\n")
}
if (result$pRRRC < alpha) {
reportTxt <- paste(reportTxt, sprintf(" Conclusion: The %s FOMs of treatments are not equal,\n F(%d,%3.2f) = %3.2f, p = %6.4f.\n\n", fom, I - 1, result$ddfRRRC, result$fRRRC, result$pRRRC),
sep = "\n")
} else {
reportTxt <- paste(reportTxt, sprintf(" Conclusion: The %s FOMs of treatments are not significantly different,\n F(%d,%3.2f) = %3.2f, p = %6.4f.\n\n", fom, I - 1, result$ddfRRRC, result$fRRRC, result$pRRRC),
sep = "\n")
}
reportTxt <- paste(reportTxt, sprintf(" b) %d%% confidence intervals for treatment differences\n", ciPercent), sep = "\n")
reportTxt <- paste(reportTxt,
sprintf(" Treatment Estimate StdErr DF t Pr > t %d%% CI ", ciPercent),
"---------- ---------- -------- -------- ------- ------ ------- -------------------",
sep = "\n")
ii <- 1
for (i in 1:I) {
if (i < I) {
for (ip in (i + 1):I) {
reportTxt <- paste(reportTxt, sprintf("%-10.10s - %-10.10s %8.5f %8.5f %7.2f %6.2f %7.4f %8.5f , %8.5f\n", dataset$modalityID[i], dataset$modalityID[ip], result$ciDiffTrtRRRC[ii, 2], result$ciDiffTrtRRRC[ii, 3],
result$ciDiffTrtRRRC[ii, 4], result$ciDiffTrtRRRC[ii, 5], result$ciDiffTrtRRRC[ii, 6], result$ciDiffTrtRRRC[ii, 7], result$ciDiffTrtRRRC[ii, 8]), sep = "\n")
ii <- ii + 1
}
}
}
reportTxt <- paste(reportTxt, "\n", sep = "\n")
if (I == 2) {
reportTxt <- paste(reportTxt, " H0: the two treatments are equal.", sep = "\n")
} else {
reportTxt <- paste(reportTxt,
sprintf(" * H0: the %d treatments are equal. To control the overall ", I),
" type I error rate at .05, we conclude that treatment differences",
" with p < .05 are significant only if the global test in ",
" (a) is also significant (i.e, p < .05).", sep = "\n")
}
if (method == "DBMH") {
reportTxt <- paste(reportTxt, " Error term: MS(TR) + max[MS(TC) - MS(TRC), 0]\n\n", sep = "\n")
} else {
reportTxt <- paste(reportTxt, " Error term: MS(TR) + J * max[Cov2 - Cov3, 0]\n\n", sep = "\n")
}
reportTxt <- paste(reportTxt,
sprintf(" c) %d%% treatment confidence intervals based on reader x case ANOVAs", ciPercent),
" for each treatment (each analysis is based only on data for the",
" specified treatment\n",
sep = "\n")
reportTxt <- paste(reportTxt,
sprintf(" Treatment Area Std Error DF %d%% Confidence Interval ", ciPercent),
" ---------- ---------- ---------- ------- -------------------------", sep = "\n")
for (i in 1:I) {
reportTxt <- paste(reportTxt, sprintf(" %-10.10s %10.8f %10.8f %7.2f (%10.8f , %10.8f)",
result$ciAvgRdrEachTrtRRRC[i, 1], result$ciAvgRdrEachTrtRRRC[i, 2], result$ciAvgRdrEachTrtRRRC[i, 3], result$ciAvgRdrEachTrtRRRC[i, 4], result$ciAvgRdrEachTrtRRRC[i, 5], result$ciAvgRdrEachTrtRRRC[i, 6]),
sep = "\n")
}
if (method == "DBMH") {
reportTxt <- paste(reportTxt, " Error term: MS(R) + max[MS(C) - MS(RC), 0]\n\n\n", sep = "\n")
} else {
reportTxt <- paste(reportTxt, "\n\n\n", sep = "\n")
}
}
reportTxt <- paste(reportTxt,
" ===========================================================================",
" ***** Analysis 2: Fixed Readers and Random Cases *****",
" ===========================================================================\n\n",
" (Results apply to the population of cases but only for the readers",
" used in this study)\n\n", sep = "\n")
reportTxt <- paste(reportTxt, sprintf(" a) Test for H0: Treatments have the same %s figure of merit.\n\n", fom), sep = "\n")
reportTxt <- paste(reportTxt,
" Source DF Mean Square F value Pr > F ",
" ---------- ------ --------------- ------- -------", sep = "\n")
if (method == "DBMH") {
if (result$pFRRC >= smallestDispalyedPval) {
reportTxt <- paste(reportTxt, sprintf(" Treatment %6d %15.8f %7.2f %7.4f", I - 1, result$anovaY[1, 4], result$fFRRC, result$pFRRC), sep = "\n")
} else {
reportTxt <- paste(reportTxt, sprintf(" Treatment %6d %15.8f %7.2f <%6.4f", I - 1, result$anovaY[1, 4], result$fFRRC, smallestDispalyedPval), sep = "\n")
}
reportTxt <- paste(reportTxt, sprintf(" Error %6.2f %15.8f", result$ddfFRRC, result$anovaY[5, 4]), sep = "\n")
reportTxt <- paste(reportTxt, " Error term: MS(TC)\n", sep = "\n")
} else {
if (result$pFRRC >= smallestDispalyedPval) {
reportTxt <- paste(reportTxt, sprintf(" Treatment %6d %15.8f %7.2f %7.4f", I - 1, result$msT, result$fFRRC, result$pFRRC), sep = "\n")
} else {
reportTxt <- paste(reportTxt, sprintf(" Treatment %6d %15.8f %7.2f <%6.4f", I - 1, result$msT, result$fFRRC, smallestDispalyedPval), sep = "\n")
}
if (J > 1) {
reportTxt <- paste(reportTxt, sprintf(" Error %6.2f %15.8f", result$ddfFRRC, (result$varComp[1, 2] - result$varComp[2, 2] + (J - 1) * (result$varComp[3, 2] - result$varComp[4, 2]))), sep = "\n")
reportTxt <- paste(reportTxt, " Error term: Var - Cov1 + (J - 1) * ( Cov2 - Cov3 )\n", sep = "\n")
} else {
reportTxt <- paste(reportTxt, sprintf(" Error %6.2f %15.8f", result$ddfFRRC, (result$varComp[1, 2] - result$varComp[2, 2])), sep = "\n")
reportTxt <- paste(reportTxt, " Error term: Var - Cov1\n", sep = "\n")
}
}
if (result$pFRRC < alpha) {
reportTxt <- paste(reportTxt, sprintf(" Conclusion: The %s FOMs of treatments are not equal,\n F(%d,%3.2f) = %3.2f, p = %6.4f.\n\n", fom, I - 1, result$ddfFRRC, result$fFRRC, result$pFRRC), sep = "\n")
} else {
reportTxt <- paste(reportTxt, sprintf(" Conclusion: The %s FOMs of treatments are not significantly different,\n F(%d,%3.2f) = %3.2f, p = %6.4f.\n\n", fom, I - 1, result$ddfFRRC, result$fFRRC, result$pFRRC),
sep = "\n")
}
reportTxt <- paste(reportTxt, sprintf(" b) %d%% confidence intervals for treatment differences\n", ciPercent), sep = "\n")
reportTxt <- paste(reportTxt,
sprintf(" Treatment Estimate StdErr DF t Pr > t %d%% CI ", ciPercent),
"---------- ---------- -------- -------- ------- ------ ------- -------------------",
sep = "\n")
ii <- 1
for (i in 1:I) {
if (i < I) {
for (ip in (i + 1):I) {
reportTxt <- paste(reportTxt, sprintf("%-10.10s - %-10.10s %8.5f %8.5f %7.2f %6.2f %7.4f %8.5f , %8.5f\n", dataset$modalityID[i], dataset$modalityID[ip], result$ciDiffTrtFRRC[ii, 2], result$ciDiffTrtFRRC[ii, 3], result$ciDiffTrtFRRC[ii,
4], result$ciDiffTrtFRRC[ii, 5], result$ciDiffTrtFRRC[ii, 6], result$ciDiffTrtFRRC[ii, 7], result$ciDiffTrtFRRC[ii, 8]), sep = "\n")
ii <- ii + 1
}
}
}
reportTxt <- paste(reportTxt, "\n", sep = "\n")
if (I == 2) {
reportTxt <- paste(reportTxt, " H0: the two treatments are equal.", sep = "\n")
} else {
reportTxt <- paste(reportTxt,
sprintf(" * H0: the %d treatments are equal. To control the overall ", I),
" type I error rate at .05, we conclude that treatment differences",
" with p < .05 are significant only if the global test in ",
" (a) is also significant (i.e, p < .05).", sep = "\n")
}
if (method == "DBMH") {
reportTxt <- paste(reportTxt, " Error term: MS(TC) \n\n", sep = "\n")
} else {
if (J > 1) {
reportTxt <- paste(reportTxt, " Error term: Var - Cov1 + (J - 1) * ( Cov2 - Cov3 )\n", sep = "\n")
} else {
reportTxt <- paste(reportTxt, " Error term: Var - Cov1\n", sep = "\n")
}
}
reportTxt <- paste(reportTxt,
sprintf(" c) %d%% treatment confidence intervals based on reader x case ANOVAs", ciPercent),
" for each treatment (each analysis is based only on data for the",
" specified treatment\n",
sep = "\n")
reportTxt <- paste(reportTxt,
sprintf(" Treatment Area Std Error DF %d%% Confidence Interval ", ciPercent),
" ---------- ---------- ---------- ------- -------------------------", sep = "\n")
for (i in 1:I) {
reportTxt <- paste(reportTxt, sprintf(" %-10.10s %10.8f %10.8f %7.2f (%10.8f , %10.8f)",
result$ciAvgRdrEachTrtFRRC[i, 1], result$ciAvgRdrEachTrtFRRC[i, 2], result$ciAvgRdrEachTrtFRRC[i, 3], result$ciAvgRdrEachTrtFRRC[i, 4],
result$ciAvgRdrEachTrtFRRC[i, 5], result$ciAvgRdrEachTrtFRRC[i, 6]), sep = "\n")
}
if (method == "DBMH") {
reportTxt <- paste(reportTxt, " Error term: MS(C) \n\n\n", sep = "\n")
} else {
if (J > 1) {
reportTxt <- paste(reportTxt, " Error term: Var - Cov1 + (J - 1) * ( Cov2 - Cov3 )\n", sep = "\n")
} else {
reportTxt <- paste(reportTxt, " Error term: Var - Cov1\n", sep = "\n")
}
}
if (method == "DBMH") {
reportTxt <- paste(reportTxt, " TREATMENT X CASE ANOVAs for each reader\n\n", sep = "\n")
reportTxt <- paste(reportTxt, " Sum of Squares", sep = "\n")
string <- " Source df "
for (j in 1:J) string <- paste0(string, sprintf("%-11.11s ", dataset$readerID[j]))
reportTxt <- paste(reportTxt, string, sep = "\n")
string <- " ------ --- "
for (j in 1:J) string <- paste0(string, sprintf("----------- ", dataset$readerID[j]))
reportTxt <- paste(reportTxt, string, sep = "\n")
string <- sprintf(" T %6d ", I - 1)
for (j in 1:J) string <- paste0(string, sprintf("%11.7f ", result$ssAnovaEachRdr[1, j + 2]))
reportTxt <- paste(reportTxt, string, sep = "\n")
string <- sprintf(" C %6d ", K - 1)
for (j in 1:J) string <- paste0(string, sprintf("%11.7f ", result$ssAnovaEachRdr[2, j + 2]))
reportTxt <- paste(reportTxt, string, sep = "\n")
string <- sprintf(" TC %6d ", (I - 1) * (K - 1))
for (j in 1:J) string <- paste0(string, sprintf("%11.7f ", result$ssAnovaEachRdr[3, j + 2]))
reportTxt <- paste(reportTxt, string, "\n\n", sep = "\n")
reportTxt <- paste(reportTxt, " Mean Squares", sep = "\n")
string <- " Source df "
for (j in 1:J) string <- paste0(string, sprintf("%-11.11s ", dataset$readerID[j]))
reportTxt <- paste(reportTxt, string, sep = "\n")
string <- " ------ --- "
for (j in 1:J) string <- paste0(string, sprintf("----------- ", dataset$readerID[j]))
reportTxt <- paste(reportTxt, string, sep = "\n")
string <- sprintf(" T %6d ", I - 1)
for (j in 1:J) string <- paste0(string, sprintf("%11.7f ", result$msAnovaEachRdr[1, j + 2]))
reportTxt <- paste(reportTxt, string, sep = "\n")
string <- sprintf(" C %6d ", K - 1)
for (j in 1:J) string <- paste0(string, sprintf("%11.7f ", result$msAnovaEachRdr[2, j + 2]))
reportTxt <- paste(reportTxt, string, sep = "\n")
string <- sprintf(" TC %6d ", (I - 1) * (K - 1))
for (j in 1:J) string <- paste0(string, sprintf("%11.7f ", result$msAnovaEachRdr[3, j + 2]))
reportTxt <- paste(reportTxt, string, "\n\n\n\n", sep = "\n")
}
reportTxt <- paste(reportTxt, " d) Treatment-by-case ANOVA CIs for each reader ", sep = "\n")
reportTxt <- paste(reportTxt, " (each analysis is based only on data for the specified reader)\n", sep = "\n")
reportTxt <- paste(reportTxt,
sprintf(" Reader Treatment Estimate StdErr DF t Pr > t %d%% CI ", ciPercent),
"---------- ---------- ---------- -------- -------- ------- ------ ------- -------------------",
sep = "\n")
l <- 1
for (j in 1:J) {
for (i in 1:I) {
if (i < I) {
for (ip in (i + 1):I) {
reportTxt <- paste(reportTxt, sprintf("%-10.10s %-10.10s-%-10.10s %8.5f %8.5f %7.2f %6.2f %7.4f %8.5f , %8.5f",
dataset$readerID[j], dataset$modalityID[i], dataset$modalityID[ip], result$ciDiffTrtEachRdr[l, 3],
result$ciDiffTrtEachRdr[l, 4], result$ciDiffTrtEachRdr[l, 5], result$ciDiffTrtEachRdr[l, 6],
result$ciDiffTrtEachRdr[l, 7], result$ciDiffTrtEachRdr[l, 8], result$ciDiffTrtEachRdr[l, 9]),
sep = "\n")
l <- l + 1
}
}
}
}
if (method == "ORH") {
string <- "\nReader Var(Error) Cov1 \n------ ---------- ----------"
reportTxt <- paste(reportTxt, string, sep = "\n")
for (j in 1:J) {
reportTxt <- paste(reportTxt, sprintf("%-6.6s %10.8s %10.8s", result$varCovEachRdr[j, 1], result$varCovEachRdr[j, 2], result$varCovEachRdr[j, 3]), sep = "\n")
}
}
reportTxt <- paste(reportTxt, "\n\n", sep = "\n")
if (J > 1) {
reportTxt <- paste(reportTxt,
" ===========================================================================",
" ***** Analysis 3: Random Readers and Fixed Cases *****",
" ===========================================================================",
" (Results apply to the population of readers but only for the cases used in this study)\n\n", sep = "\n")
reportTxt <- paste(reportTxt, sprintf(" a) Test for H0: Treatments have the same %s figure of merit.\n\n", fom), sep = "\n")
reportTxt <- paste(reportTxt,
" Source DF Mean Square F value Pr > F ",
" ---------- ------ --------------- ------- -------", sep = "\n")
if (method == "DBMH") {
if (result$pRRFC >= smallestDispalyedPval) {
reportTxt <- paste(reportTxt, sprintf(" Treatment %6d %15.8f %7.2f %7.4f", I - 1, result$anovaY[1, 4], result$fRRFC, result$pRRFC), sep = "\n")
} else {
reportTxt <- paste(reportTxt, sprintf(" Treatment %6d %15.8f %7.2f <%6.4f", I - 1, result$anovaY[1, 4], result$fRRFC, smallestDispalyedPval), sep = "\n")
}
reportTxt <- paste(reportTxt, sprintf(" Error %6.2f %15.8f", result$ddfRRFC, result$anovaY[4, 4]), sep = "\n")
} else {
if (result$pRRFC >= smallestDispalyedPval) {
reportTxt <- paste(reportTxt, sprintf(" Treatment %6d %15.8f %7.2f %7.4f", I - 1, result$msT, result$fRRFC, result$pRRFC), sep = "\n")
} else {
reportTxt <- paste(reportTxt, sprintf(" Treatment %6d %15.8f %7.2f <%6.4f", I - 1, result$msT, result$fRRFC, smallestDispalyedPval), sep = "\n")
}
reportTxt <- paste(reportTxt, sprintf(" Error %6.2f %15.8f", result$ddfRRFC, result$msTR), sep = "\n")
}
reportTxt <- paste(reportTxt, " Error term: MS(TR)\n", sep = "\n")
if (result$pRRFC < alpha) {
reportTxt <- paste(reportTxt, sprintf(" Conclusion: The %s FOMs of treatments are not equal,\n F(%d,%3.2f) = %3.2f, p = %6.4f.\n\n", fom, I - 1, result$ddfRRFC, result$fRRFC, result$pRRFC),
sep = "\n")
} else {
reportTxt <- paste(reportTxt, sprintf(" Conclusion: The %s FOMs of treatments are not significantly different,\n F(%d,%3.2f) = %3.2f, p = %6.4f.\n\n", fom, I - 1, result$ddfRRFC, result$fRRFC, result$pRRFC),
sep = "\n")
}
reportTxt <- paste(reportTxt, sprintf(" b) %d%% confidence intervals for treatment differences\n", ciPercent), sep = "\n")
reportTxt <- paste(reportTxt,
sprintf(" Treatment Estimate StdErr DF t Pr > t %d%% CI ", ciPercent),
"---------- ---------- -------- -------- ------- ------ ------- -------------------",
sep = "\n")
ii <- 1
for (i in 1:I) {
if (i < I) {
for (ip in (i + 1):I) {
reportTxt <- paste(reportTxt, sprintf("%-10.10s - %-10.10s %8.5f %8.5f %7.2f %6.2f %7.4f %8.5f , %8.5f\n",
dataset$modalityID[i], dataset$modalityID[ip], result$ciDiffTrtRRFC[ii, 2],
result$ciDiffTrtRRFC[ii, 3], result$ciDiffTrtRRFC[ii, 4], result$ciDiffTrtRRFC[ii, 5],
result$ciDiffTrtRRFC[ii, 6], result$ciDiffTrtRRFC[ii, 7], result$ciDiffTrtRRFC[ii, 8]),
sep = "\n")
ii <- ii + 1
}
}
}
reportTxt <- paste(reportTxt, "\n", sep = "\n")
if (I == 2) {
reportTxt <- paste(reportTxt, " H0: the two treatments are equal.", sep = "\n")
} else {
reportTxt <- paste(reportTxt,
sprintf(" * H0: the %d treatments are equal. To control the overall ", I),
" type I error rate at .05, we conclude that treatment differences",
" with p < .05 are significant only if the global test in ",
" (a) is also significant (i.e, p < .05).", sep = "\n")
}
reportTxt <- paste(reportTxt, "\n\n", sep = "\n")
reportTxt <- paste(reportTxt,
" c) Reader-by-case ANOVAs for each treatment (each analysis is based only on data for the",
" specified treatment\n", sep = "\n")
reportTxt <- paste(reportTxt,
sprintf(" Treatment Area Std Error DF %d%% Confidence Interval ", ciPercent),
" ---------- ---------- ---------- ------- -------------------------", sep = "\n")
for (i in 1:I) {
reportTxt <- paste(reportTxt, sprintf(" %-10.10s %10.8f %10.8f %7.2f (%10.8f , %10.8f)",
result$ciAvgRdrEachTrtRRFC[i, 1], result$ciAvgRdrEachTrtRRFC[i, 2],
result$ciAvgRdrEachTrtRRFC[i, 3], result$ciAvgRdrEachTrtRRFC[i, 4],
result$ciAvgRdrEachTrtRRFC[i, 5], result$ciAvgRdrEachTrtRRFC[i, 6]),
sep = "\n")
}
}
return (reportTxt)
}
shinyServer(function(input, output) {
#source("system.file(\"GUI\", \"ReportTextForGUI.R\", package = \"RJafroc\")")
values <- reactiveValues()
output$ui <- renderUI({
if (is.null(input$dataFile)){
wellPanel(
p(paste0("RJafroc SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ",
"IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ",
"FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ",
"AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ",
"LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ",
"OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS ",
"IN THE SOFTWARE."), style = "font-size:12pt")
)
}else{
fileName <- paste0(input$dataFile$datapath, ".", file_ext(input$dataFile$name))
file.rename(input$dataFile$datapath, fileName)
if (file_ext(input$dataFile$name) %in% c("xls", "xlsx")){
dataset <- ReadDataFile(fileName)
}else if (file_ext(input$dataFile$name) %in% c("txt", "csv", "lrc")){
dataset <- ReadDataFile(fileName, format = "MRMC")
}else if (file_ext(input$dataFile$name) == "imrmc"){
dataset <- ReadDataFile(fileName, format = "iMRMC")
}else{
stop("Invalid data format.")
}
values$dataset <- dataset
fomBtn <- list()
if (dataset$dataType == "ROC"){
fomBtn[[1]] <- c("Wilcoxon" = "Wilcoxon",
"HrSe" = "HrSe",
"HrSp" = "HrSp",
"SongA1" = "SongA1",
"SongA2" = "SongA2",
"MaxLLF" = "MaxLLF",
"MaxNLF" = "MaxNLF",
"MaxNLFAllCases" = "MaxNLFAllCases",
"ExpTrnsfmSp" = "ExpTrnsfmSp",
"JAFROC" = "JAFROC",
"Weighted JAFROC" = "wJAFROC",
"JAFROC1" = "JAFROC1",
"Weighted JAFROC1" = "wJAFROC1")
fomBtn <- list(
radioButtons("fom", "Figure of Merit",
fomBtn[[1]],
inline = TRUE,
selected = "wJAFROC"
)
)
}else if (dataset$dataType == "FROC"){
fomBtn[[1]] <- c("HrAuc" = "HrAuc",
"HrSe" = "HrSe",
"HrSp" = "HrSp",
"SongA1" = "SongA1",
"SongA2" = "SongA2",
"MaxLLF" = "MaxLLF",
"MaxNLF" = "MaxNLF",
"MaxNLFAllCases" = "MaxNLFAllCases",
"ExpTrnsfmSp" = "ExpTrnsfmSp",
"JAFROC" = "JAFROC",
"Weighted JAFROC" = "wJAFROC",
"JAFROC1" = "JAFROC1",
"Weighted JAFROC1" = "wJAFROC1")
fomBtn <- list(
radioButtons("fom", "Figure of Merit",
fomBtn[[1]],
inline = TRUE,
selected = "wJAFROC"
)
)
}else if (dataset$dataType == "ROI"){
fomBtn[[1]] <- c("ROI" = "ROI")
fomBtn <- radioButtons("fom", "Figure of Merit",
fomBtn[[1]],
inline = TRUE
)
}
trtGroup <- as.list(1:length(dataset$modalityID))
rdrGroup <- as.list(1:length(dataset$readerID))
names(trtGroup) <- dataset$modalityID
names(rdrGroup) <- dataset$readerID
values$trtGroup <- trtGroup
values$rdrGroup <- rdrGroup
fluidPage(
tabsetPanel(type = "tabs",
tabPanel("Data Viewer",
tabsetPanel(type = "tabs",
tabPanel("Truth", tableOutput("truthTable")),
tabPanel("NL", tableOutput("nlTable")),
tabPanel("LL", tableOutput("llTable")),
tabPanel("Data Conversion", uiOutput("dataCnvt"))
)
),
tabPanel("Analysis",
div(sidebarLayout(
sidebarPanel(
wellPanel(
p(sprintf("Data type: %s", dataset$dataType)),
p(sprintf("Number of modalities: %d", length(dataset$modalityID))),
p(sprintf("Number of readers: %d", length(dataset$readerID))),
p(sprintf("Number of normal cases: %d", dim(dataset$NL)[3])),
p(sprintf("Number of abnormal cases: %d", dim(dataset$LL)[3]))
),
radioButtons("mthd", "Analysis Methods:",
c("DBMH" = "DBMH",
"ORH" = "ORH"),
inline = TRUE
),
fomBtn,
uiOutput("covEstBtn"),
uiOutput("nBootsBtn"),
textInput("alpha", HTML("Significance Level (α)"), value = 0.05),
actionButton("analyzeBtn", "Analyze"),
downloadButton("downloadReportBtn", "Save Report", class = NULL),
width = 4
),
mainPanel(
tags$style(type='text/css', '#report {font-size: 8pt}'),
verbatimTextOutput("report"),
width = 8
)
),
style = 'width:1200px;'
)
),
tabPanel("Plotting",
div(sidebarLayout(
sidebarPanel(
uiOutput("plotboxes"),
actionButton("nGroup", "Add a plotting group"),
width = 4
),
mainPanel(
uiOutput("plots")
)
),
style = 'width:1200px;'
)
),
tabPanel("Sample Size",
tabsetPanel(type = "tabs",
tabPanel("For input data file",
div(sidebarLayout(
sidebarPanel(
textInput("alphaDataPower", HTML("Significance Level (α)"), value = 0.05),
textInput("effectSizeDataPower", "Effect Size", value = 0.05),
textInput("desiredDataPower", "Desired Power", value = 0.8),
radioButtons("randomDataPower", "Random Option:",
c("ALL" = "ALL",
"READERS" = "READERS",
"CASES" = "CASES"),
inline = TRUE
),
actionButton("calculateDataPowerBtn", "Calculate"),
width = 4
),
mainPanel(
wellPanel(
tableOutput("powerTable")
),
width = 8
)
),
style = 'width:1100px;'
)
),
tabPanel("Use variance components",
div(sidebarLayout(
sidebarPanel(
textInput("JSampleSize", "Number of Readers"),
radioButtons("compType", "Analysis Methods:",
c("DBMH" = "DBMH",
"ORH" = "ORH"),
inline = TRUE
),
uiOutput("varComp"),
textInput("alphaSampleSize", HTML("Significance Level (α)"), value = 0.05),
textInput("effectSizeSampleSize", "Effect Size", value = 0.05),
textInput("desiredSampleSize", "Desired Power", value = 0.8),
radioButtons("randomSampleSize", "Random Option:",
c("ALL" = "ALL",
"READERS" = "READERS",
"CASES" = "CASES"),
inline = TRUE
),
actionButton("calculateSampleSizeBtn", "Calculate"),
width = 4
),
mainPanel(
verbatimTextOutput("sampleSize"),
width = 8
)
),
style = 'width:1200px;'
)
)
)
)
)
)
}
})
output$dataCnvt <- renderUI({
dataset <- values$dataset
if (dataset$dataType == "FROC"){
list(
p(sprintf("Data type: %s", dataset$dataType)),
checkboxInput("ifHr", "Highest Rating Inferred ROC"),
uiOutput("FROCFormat")
)
}else if (dataset$dataType == "ROC"){
values$cnvtedDataset <- values$dataset
list(
p(sprintf("Data type: %s", dataset$dataType)),
radioButtons("saveFormat", "Save As:",
c("JAFROC" = "JAFROC",
"MRMC(.csv)" = "MRMCCSV",
"MRMC(.lrc)" = "MRMCLRC",
"iMRMC" = "iMRMC"),
inline = TRUE
),
downloadButton("saveCnvted", "Save")
)
}
})
output$FROCFormat <- renderUI({
if (input$ifHr){
values$cnvtedDataset <- FROC2HrROC(values$dataset)
list(
radioButtons("saveFormat", "Save As:",
c("JAFROC" = "JAFROC",
"MRMC(.csv)" = "MRMCCSV",
"MRMC(.lrc)" = "MRMCLRC",
"iMRMC" = "iMRMC"),
inline = TRUE
),
downloadButton("saveCnvted", "Save")
)
}else{
values$cnvtedDataset <- values$dataset
list(
radioButtons("saveFormat", "Save As:",
c("JAFROC" = "JAFROC"),
inline = TRUE
),
downloadButton("saveCnvted", "Save")
)
}
})
output$saveCnvted <- downloadHandler(
filename = function() {
if (input$saveFormat == "JAFROC"){
paste("data", ".xlsx", sep="")
}else if (input$saveFormat == "MRMCCSV"){
paste("data", ".csv", sep="")
}else if (input$saveFormat == "MRMCLRC"){
paste("data", ".lrc", sep="")
}else if (input$saveFormat == "iMRMC"){
paste("data", ".imrmc", sep="")
}
},
content = function(file) {
if (input$saveFormat == "JAFROC"){
SaveDataFile(values$cnvtedDataset, fileName = file, format = "JAFROC")
}else if (input$saveFormat == "MRMCCSV"){
SaveDataFile(values$cnvtedDataset, fileName = file, format = "MRMC")
}else if (input$saveFormat == "MRMCLRC"){
SaveDataFile(values$cnvtedDataset, fileName = file, format = "MRMC")
}else if (input$saveFormat == "iMRMC"){
SaveDataFile(values$cnvtedDataset, fileName = file, format = "iMRMC")
}
}
)
output$powerTable <- renderTable({
if (input$calculateDataPowerBtn == 0){
NULL
}else{
input$calculateDataPowerBtn
isolate(PowerTable(values$dataset, alpha = as.numeric(input$alphaDataPower),
effectSize = as.numeric(input$effectSizeDataPower),
desiredPower = as.numeric(input$desiredDataPower),
randomOption = input$randomDataPower))
}
})
output$sampleSize <- renderText({
if (input$calculateSampleSizeBtn == 0){
NULL
}else{
input$calculateSampleSizeBtn
isolate({
sampSize <- SampleSizeGivenJ(J = as.numeric(input$JSampleSize),
varYTR = as.numeric(input$varYTR), varYTC = as.numeric(input$varYTC),
varYEps = as.numeric(input$varYEps), cov1 = as.numeric(input$cov1),
cov2 = as.numeric(input$cov2), cov3 = as.numeric(input$cov3),
varEps = as.numeric(input$varEps), msTR = as.numeric(input$msTR),
KStar = as.numeric(input$KStar),
alpha = as.numeric(input$alphaSampleSize),
effectSize = as.numeric(input$effectSizeSampleSize),
desiredPower = as.numeric(input$desiredSampleSize),
randomOption = input$randomSampleSize)
sprintf("The required number of cases for desired power %f is %d.", sampSize$power, sampSize$K)
})
}
})
output$varComp <- renderUI({
if (input$compType == "DBMH"){
list(
textInput("varYTR", "VAR(TR)"),
textInput("varYTC", "VAR(TC)"),
textInput("varYEps", "VAR(ERROR)")
)
}else{
list(
textInput("cov1", "COV1"),
textInput("cov2", "COV2"),
textInput("cov3", "COV3"),
textInput("varEps", "VAR(ERROR)"),
textInput("msTR", "MS(T*R)"),
textInput("KStar", "Number of Cases in Pilot Study")
)
}
})
output$plots <- renderUI({
if (values$dataset$dataType == "ROC"){
wellPanel(
p("ROC Curve"),
p(
downloadButton("downloadROCPlot", "Save ROC Plot"),
downloadButton("downloadROCPoints", "Save ROC Points")
),
plotOutput("ROCPlot")
)
}else{
list(
splitLayout(
wellPanel(
p("ROC Curve"),
p(
downloadButton("downloadROCPlot", "Save ROC Plot"),
downloadButton("downloadROCPoints", "Save ROC Points")
),
plotOutput("ROCPlot")
),
wellPanel(
p("AFROC Curve"),
p(
downloadButton("downloadAFROCPlot", "Save AFROC Plot"),
downloadButton("downloadAFROCPoints", "Save AFROC Points")
),
plotOutput("AFROCPlot")
)
),
splitLayout(
wellPanel(
p("FROC Curve"),
p(
downloadButton("downloadFROCPlot", "Save FROC Plot"),
downloadButton("downloadFROCPoints", "Save FROC Points")
),
plotOutput("FROCPlot")
),
cellWidths = "50%"
)
)
}
})
output$downloadROCPlot <- downloadHandler(
filename = function() {
paste("ROCPlot", ".png", sep="")
},
content = function(file) {
device <- function(..., width, height) {
grDevices::png(..., width = width, height = height,
res = 300, units = "in")
}
ggsave(file, values$ROCPlot, device = device)
}
)
output$downloadROCPoints <- downloadHandler(
filename = function() {
paste("ROCPoints", ".csv", sep="")
},
content = function(file) {
ROCPoints <- values$ROCPoints
modalities <- unlist(lapply(strsplit(as.character(ROCPoints$class), split = "\n"), "[[", 1))
readers <- unlist(lapply(strsplit(as.character(ROCPoints$class), split = "\n"), "[[", 2))
ROCPoints <- data.frame(FPF = ROCPoints$FPF, TPF = ROCPoints$TPF, Modality = modalities, Reader = readers)
write.csv(ROCPoints, file, row.names = FALSE)
}
)
output$downloadAFROCPlot <- downloadHandler(
filename = function() {
paste("AFROCPlot", ".png", sep="")
},
content = function(file) {
device <- function(..., width, height) {
grDevices::png(..., width = width, height = height,
res = 300, units = "in")
}
ggsave(file, values$AFROCPlot, device = device)
}
)
output$downloadAFROCPoints <- downloadHandler(
filename = function() {
paste("AFROCPoints", ".csv", sep="")
},
content = function(file) {
AFROCPoints <- values$AFROCPoints
modalities <- unlist(lapply(strsplit(as.character(AFROCPoints$class), split = "\n"), "[[", 1))
readers <- unlist(lapply(strsplit(as.character(AFROCPoints$class), split = "\n"), "[[", 2))
AFROCPoints <- data.frame(FPF = AFROCPoints$FPF, TPF = AFROCPoints$TPF, Modality = modalities, Reader = readers)
write.csv(AFROCPoints, file, row.names = FALSE)
}
)
output$downloadFROCPlot <- downloadHandler(
filename = function() {
paste("FROCPlot", ".png", sep="")
},
content = function(file) {
device <- function(..., width, height) {
grDevices::png(..., width = width, height = height,
res = 300, units = "in")
}
ggsave(file, values$FROCPlot, device = device)
}
)
output$downloadFROCPoints <- downloadHandler(
filename = function() {
paste("FROCPoints", ".csv", sep="")
},
content = function(file) {
FROCPoints <- values$FROCPoints
modalities <- unlist(lapply(strsplit(as.character(FROCPoints$class), split = "\n"), "[[", 1))
readers <- unlist(lapply(strsplit(as.character(FROCPoints$class), split = "\n"), "[[", 2))
FROCPoints <- data.frame(FPF = FROCPoints$FPF, TPF = FROCPoints$TPF, Modality = modalities, Reader = readers)
write.csv(FROCPoints, file, row.names = FALSE)
}
)
output$ROCPlot <- renderPlot({
trts <- values$trts
rdrs <- values$rdrs
if (length(trts) == 0 || length(rdrs) == 0){
NULL
}else{
if (length(trts) > 5 || length(rdrs) > 5){
ROCPlot <- EmpiricalOpCharac(values$dataset, trts, rdrs, lgdPos = "right", opChType = "ROC")
values$trts <- trts
values$rdrs <- rdrs
values$ROCPlot <- ROCPlot$ROCPlot
values$ROCPoints <- ROCPlot$ROCPoints
values$ROCPlot
}else{
ROCPlot <- EmpiricalOpCharac(values$dataset, trts, rdrs, opChType = "ROC")
values$trts <- trts
values$rdrs <- rdrs
values$ROCPlot <- ROCPlot$ROCPlot
values$ROCPoints <- ROCPlot$ROCPoints
values$ROCPlot
}
}
})
output$AFROCPlot <- renderPlot({
trts <- values$trts
rdrs <- values$rdrs
if (length(trts) == 0 || length(rdrs) == 0){
NULL
}else{
if (length(trts) > 5 || length(rdrs) > 5){
AFROCPlot <- EmpiricalOpCharac(values$dataset, trts, rdrs, lgdPos = "right", opChType = "AFROC")
values$trts <- trts
values$rdrs <- rdrs
values$AFROCPlot <- AFROCPlot$AFROCPlot
values$AFROCPoints <- AFROCPlot$AFROCPoints
values$AFROCPlot
}else{
AFROCPlot <- EmpiricalOpCharac(values$dataset, trts, rdrs, opChType = "AFROC")
values$trts <- trts
values$rdrs <- rdrs
values$AFROCPlot <- AFROCPlot$AFROCPlot
values$AFROCPoints <- AFROCPlot$AFROCPoints
values$AFROCPlot
}
}
})
output$FROCPlot <- renderPlot({
trts <- values$trts
rdrs <- values$rdrs
if (length(trts) == 0 || length(rdrs) == 0){
NULL
}else{
if (length(trts) > 5 || length(rdrs) > 5){
FROCPlot <- EmpiricalOpCharac(values$dataset, trts, rdrs, lgdPos = "right", opChType = "FROC")
values$trts <- trts
values$rdrs <- rdrs
values$FROCPlot <- FROCPlot$FROCPlot
values$FROCPoints <- FROCPlot$FROCPoints
values$FROCPlot
}else{
FROCPlot <- EmpiricalOpCharac(values$dataset, trts, rdrs, opChType = "FROC")
values$trts <- trts
values$rdrs <- rdrs
values$FROCPlot <- FROCPlot$FROCPlot
values$FROCPoints <- FROCPlot$FROCPoints
values$FROCPlot
}
}
})
output$downloadReportBtn <- downloadHandler(
filename = function() {
paste0(paste(file_path_sans_ext(input$dataFile$name), input$mthd, input$fom, sep="_"), ".txt")
},
content = function(file) {
write(values$reportStrings, file)
}
)
output$report <- renderText({
if (input$analyzeBtn == 0){
"Click \"Analyze\" to generate analysis report."
}else{
input$analyzeBtn
values$reportStrings <- isolate(ReportTextForGUI(dataset = values$dataset, method = input$mthd, fom = input$fom,
alpha = as.numeric(input$alpha), covEstMethod = input$covEstMthd,
nBoots = as.numeric(input$nBoots)))
}
})
output$plotboxes <- renderUI({
trtGroup <- values$trtGroup
rdrGroup <- values$rdrGroup
ret <- reactiveValuesToList(input)
plotList <- list()
for (i in 1:(input$nGroup + 1)){
if (paste0("plotTrts", i) %in% names(ret)){
plotList <- c(plotList,
list(
wellPanel(
checkboxGroupInput(paste0("plotTrts", i),
"Modalities: ",
trtGroup,
get(paste0("plotTrts", i), ret),
inline = TRUE),
checkboxGroupInput(paste0("plotRdrs", i),
"Readers: ",
rdrGroup,
get(paste0("plotRdrs", i), ret),
inline = TRUE),
checkboxInput(paste0("ifAvg", i),
"Averaged Curve?",
get(paste0("ifAvg", i), ret))
)
)
)
}else{
plotList <- c(plotList,
list(
wellPanel(
checkboxGroupInput(paste0("plotTrts", i),
"Modalities: ",
trtGroup,
inline = TRUE),
checkboxGroupInput(paste0("plotRdrs", i),
"Readers: ",
rdrGroup,
inline = TRUE),
checkboxInput(paste0("ifAvg", i),
"Averaged Curve?")
)
)
)
}
}
selectGroup <- NULL
for (i in 1:(1 + input$nGroup)){
groupTrt <- as.numeric(ret[[paste0("plotTrts", i)]])
groupRdr <- as.numeric(ret[[paste0("plotRdrs", i)]])
if (length(groupTrt) == 0 || length(groupRdr) == 0) next
selectGroup <- c(selectGroup, i)
}
if (!is.null(selectGroup) && length(selectGroup) == 1 && !ret[[paste0("ifAvg", selectGroup)]]){
trts <- as.numeric(ret[[paste0("plotTrts", selectGroup)]])
rdrs <- as.numeric(ret[[paste0("plotRdrs", selectGroup)]])
}else{
trts <- list()
rdrs <- list()
for (i in 1:(input$nGroup + 1)){
ifAvg <- ret[[paste0("ifAvg", i)]]
if (length(ifAvg) != 0 && ifAvg){
groupTrt <- as.numeric(ret[[paste0("plotTrts", i)]])
groupRdr <- as.numeric(ret[[paste0("plotRdrs", i)]])
if (length(groupTrt) == 0 || length(groupRdr) == 0) next
trts <- c(
trts,
list(groupTrt)
)
rdrs <- c(
rdrs,
list(groupRdr)
)
}else{
allComb <- expand.grid(as.list(as.numeric(ret[[paste0("plotTrts", i)]])),
as.list(as.numeric(ret[[paste0("plotRdrs", i)]])))
if (nrow(allComb) == 0) next
trts <- c(
trts,
as.list(as.numeric(allComb[ , 1]))
)
rdrs <- c(
rdrs,
as.list(as.numeric(allComb[ , 2]))
)
}
}
}
values$trts <- trts
values$rdrs <- rdrs
plotList
})
output$covEstBtn <- renderUI({
if (is.null(input$mthd)){
NULL
}else if (input$mthd == "DBMH"){
NULL
}else if (input$mthd == "ORH") {
if (input$fom %in% c("Wilcoxon", "HrAuc", "ROI")){
if (is.null(input$covEstMthd)){
radioButtons("covEstMthd", "Covariances Estimate Method:",
c("Jackknife" = "Jackknife",
"Bootstrap" = "Bootstrap",
"DeLong" = "DeLong"
),
inline = TRUE
)
}else{
radioButtons("covEstMthd", "Covariances Estimate Method:",
c("Jackknife" = "Jackknife",
"Bootstrap" = "Bootstrap",
"DeLong" = "DeLong"
),
inline = TRUE,
selected = input$covEstMthd
)
}
}else{
if (is.null(input$covEstMthd) || input$covEstMthd == "DeLong"){
radioButtons("covEstMthd", "Covariances Estimate Method:",
c("Jackknife" = "Jackknife",
"Bootstrap" = "Bootstrap"
),
inline = TRUE
)
}else{
radioButtons("covEstMthd", "Covariances Estimate Method:",
c("Jackknife" = "Jackknife",
"Bootstrap" = "Bootstrap"
),
inline = TRUE,
selected = input$covEstMthd
)
}
}
}
})
output$nBootsBtn <- renderUI({
if (input$mthd == "DBMH"){
NULL
}else{
if (is.null(input$covEstMthd)){
NULL
}else if (input$covEstMthd == "Bootstrap"){
textInput("nBoots", "Number of Bootstrapping", value = 200)
}else{
NULL
}
}
})
output$truthTable <- renderTable({
dataset <- values$dataset
NL <- dataset$NL
LL <- dataset$LL
lesionNum <- dataset$lesionNum
lesionID <- dataset$lesionID
lesionWeight <- dataset$lesionWeight
maxNL <- dim(NL)[4]
dataType <- dataset$dataType
modalityID <- dataset$modalityID
readerID <- dataset$readerID
I <- length(modalityID)
J <- length(readerID)
K <- dim(NL)[3]
K2 <- dim(LL)[3]
K1 <- K - K2
caseIDs <- c(1:K1, rep(K1 + 1:K2, lesionNum))
lesionIDs <- as.vector(t(lesionID))
lesionIDs <- lesionIDs[lesionIDs != -Inf]
lesionIDs <- c(rep(0, K1), lesionIDs)
lesionWeights <- as.vector(t(lesionWeight))
lesionWeights <- lesionWeights[lesionWeights != -Inf]
lesionWeights <- c(rep(0, K1), lesionWeights)
data.frame(CaseID = caseIDs, LesionID = as.integer(lesionIDs), Weight = lesionWeights)
})
output$nlTable <- renderTable({
dataset <- values$dataset
NL <- dataset$NL
LL <- dataset$LL
lesionNum <- dataset$lesionNum
lesionID <- dataset$lesionID
lesionWeight <- dataset$lesionWeight
maxNL <- dim(NL)[4]
dataType <- dataset$dataType
modalityID <- dataset$modalityID
readerID <- dataset$readerID
I <- length(modalityID)
J <- length(readerID)
K <- dim(NL)[3]
K2 <- dim(LL)[3]
K1 <- K - K2
dataSheet <- NULL
for (i in 1:I) {
for (j in 1:J) {
for (k in 1:K) {
for (l in 1:maxNL) {
if (NL[i, j, k, l] != -Inf) {
dataSheet <- rbind(dataSheet, c(j, i, k, NL[i, j, k, l]))
}
}
}
}
}
data.frame(ReaderID = readerID[dataSheet[, 1]], ModalityID = modalityID[dataSheet[, 2]], CaseID = as.integer(dataSheet[, 3]), NL_Rating = signif(dataSheet[, 4], 6))
})
output$llTable <- renderTable({
dataset <- values$dataset
NL <- dataset$NL
LL <- dataset$LL
lesionNum <- dataset$lesionNum
lesionID <- dataset$lesionID
lesionWeight <- dataset$lesionWeight
maxNL <- dim(NL)[4]
dataType <- dataset$dataType
modalityID <- dataset$modalityID
readerID <- dataset$readerID
I <- length(modalityID)
J <- length(readerID)
K <- dim(NL)[3]
K2 <- dim(LL)[3]
K1 <- K - K2
dataSheet <- NULL
for (i in 1:I) {
for (j in 1:J) {
for (k in 1:K2) {
for (l in 1:lesionNum[k]) {
if (LL[i, j, k, l] != -Inf) {
dataSheet <- rbind(dataSheet, c(j, i, k + K1, lesionID[k, l], LL[i, j, k, l]))
}
}
}
}
}
data.frame(ReaderID = readerID[dataSheet[, 1]], ModalityID = modalityID[dataSheet[, 2]], CaseID = as.integer(dataSheet[, 3]), LesionID = as.integer(dataSheet[, 4]), LL_Rating = signif(dataSheet[, 5], 6))
})
}) |
b0d8c7af14e492c5f7c1a9cfbe7cf2621afa23c8 | ad184b82a6d1d74f7ed3110c5bccf10719170bd7 | /man/check_r_causact_env.Rd | 17acb925b2cf7ac0b946c7b654099bdabfa4d554 | [
"MIT"
] | permissive | flyaflya/causact | 5a5f695e92ac79997de2fd291845f8ed51b05805 | 17c374a9c039c0d5726931953d97985d87d7dcaa | refs/heads/master | 2023-08-31T13:00:47.344039 | 2023-08-19T13:27:50 | 2023-08-19T13:27:50 | 130,230,186 | 39 | 15 | NOASSERTION | 2022-06-02T14:09:58 | 2018-04-19T14:42:45 | R | UTF-8 | R | false | true | 289 | rd | check_r_causact_env.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/utils.R
\name{check_r_causact_env}
\alias{check_r_causact_env}
\title{Check if 'r-causact' Conda environment exists}
\usage{
check_r_causact_env()
}
\description{
Check if 'r-causact' Conda environment exists
}
|
b0a786713873bdcd73aa093dbe5b67866de0675f | 661d4d3f14e14b699c697efc8db05a220ed40eb9 | /mosaicApps/mosaicManipShiny/mDensity/mDensity.R | 92cf7ece1e84825654ed4c0409997896083a5e2c | [] | no_license | dtkaplan/MOSAIC-Summer-2015 | 60518bb08edb3c7165ddb5e74104ccdfdb1c0225 | 2f97827b9e09fccc7cc5679888fe3000d71fe1cc | refs/heads/master | 2021-01-23T13:31:24.897643 | 2015-11-17T22:39:39 | 2015-11-17T22:39:39 | 35,576,261 | 0 | 1 | null | 2015-06-02T21:24:26 | 2015-05-13T21:58:29 | R | UTF-8 | R | false | false | 367 | r | mDensity.R |
myFun=function(bandwidth, dist, trans, npts, ...){
if(dist=="Normal")
x=rnorm(npts, mean=0, sd=5)
if(dist=="Uniform")
x=runif(npts, min=-10, max=10)
if(dist=="Exponential")
x=rexp(npts, rate=1)
trans.x=trans(x)
dens = densityplot(trans.x, xlab= "Values", bw=bandwidth,
scales = list(x=list(cex=1.5)))
print(dens)
}
|
fa0b971c68e016a5173c449a6d617ce1013cad08 | 2de826713dade1f40a8dbb08d07a550f02ebb846 | /ui.R | 3c8476ebeb207648d5912feb6636a8f66591a6f2 | [] | no_license | jamesfuller-cdc/chainchecker-godata | 2d5ed1aa2eae9ad7fc4aaaa476aa0e483bb93e7c | 909a5d4471382dc0e7bd8e30ab1942f8e012455b | refs/heads/master | 2023-03-17T09:21:43.983083 | 2020-02-26T15:47:54 | 2020-02-26T15:47:54 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 6,385 | r | ui.R | library(shiny)
library(shinythemes)
library(plotly)
library(shinycssloaders)
navbarPage(title = "chainchecker",
selected = "Home",
theme = shinytheme("cerulean"),
tabPanel("Home",
icon = icon("home"),
radioButtons(inputId = "language",
label = "",
choiceValues = c("en", "fr"),
choiceNames = c("English", "Français"),
selected = "en",
inline = TRUE),
uiOutput("aboutUI")
),
# Sidebar with a slider input for number of bins
tabPanel("Timeline",
icon = icon("stream"),
sidebarPanel(
uiOutput("min_incubUI"),
uiOutput("max_incubUI"),
uiOutput("onset_deathUI"),
uiOutput("idUI"),
#conditions
uiOutput("dod_avail_checkUI"),
conditionalPanel(
condition = "input.death_avail == true",
uiOutput("dodUI")
),
conditionalPanel(
condition = "input.death_avail == false",
uiOutput("dosoUI"),
uiOutput("bleeding_checkUI"),
conditionalPanel(
condition = "input.bleeding_at_reported_onset == true",
uiOutput("onset_bleedingUI")),
conditionalPanel(
condition = "input.bleeding_at_reported_onset == false",
uiOutput("diarrhea_checkUI"),
conditionalPanel(
condition = "input.diarrhea_at_reported_onset == true",
uiOutput("onset_diarrheaUI"))
)
),
uiOutput("hoverUI")
),
mainPanel(plotlyOutput("exposure_plot"),
textOutput("estimated_onset"),
textOutput("exposure_window"))
),
tabPanel("Upload",
icon = icon("upload"),
sidebarPanel(
uiOutput("download_lUI"),
br(),br(),
uiOutput("download_cUI"),
uiOutput("upload_lUI"),
uiOutput("upload_cUI")),
mainPanel(
uiOutput("upload_guideUI")
)
),
tabPanel("Exposure windows",
icon = icon("poll-h"),
sidebarPanel(
uiOutput("check_dates_reportedUI"),
#standard inputs
uiOutput("min_incub_allUI"),
uiOutput("max_incub_allUI"),
uiOutput("onset_death_allUI"),
uiOutput("onset_bleeding_allUI"),
uiOutput("onset_diarrhea_allUI"),
uiOutput("enter_id1UI"),
textInput("ID2_onset_window",
"", placeholder = "EG2"),
br(),br(),
uiOutput("download_windowUI"),
br(),br(),
uiOutput("dates_of_deathUI")
),
mainPanel(plotlyOutput("onset_plot") %>% withSpinner(type = 5, color = "orange"))
),
tabPanel("Transmission tree",
icon = icon("link"),
sidebarPanel(
uiOutput("adjust_treeUI"),
uiOutput("linelist_group"),
uiOutput("contact_group"),
uiOutput("tooltip_options"),
br(),br(),
uiOutput("tree_downloadUI"),
br(),br(),
uiOutput("contact_downloadUI"),
br(),br(),
plotOutput("link_legend", height = "100px")
),
mainPanel( plotlyOutput("tree") %>% withSpinner(type = 5, color = "orange") )
),
tabPanel("Cluster plots",
icon = icon("project-diagram"),
sidebarPanel(
uiOutput("hover2UI"),
br(),br(),
uiOutput("download_clUI")
),
mainPanel(plotlyOutput("network",width="1200px",height="800px") %>%
withSpinner(type = 5, color = "orange"))),
tabPanel("Cluster Information",
icon = icon("table"),
DT::dataTableOutput("networkTable")
),
tabPanel("Method and definitions",
icon = icon("book"),
uiOutput("methodUI")
)
)
|
8fa2edc9f9f06724d373dd7e7194c81ce058e98c | 8eaf931982f7e38b1a5fd934f2da31383edb459f | /ui.R | 90afcb148a8ec0a3ac0c502b6161fe89a47f1ad3 | [
"MIT"
] | permissive | alexdum/roclib | a1b0356ab43b287ffcbba3c9a518f9f4f229c3c9 | e82696ce5e6437eebebc5e885ecdb82fa2c79edd | refs/heads/main | 2023-08-29T17:13:57.795073 | 2021-11-15T20:55:28 | 2021-11-15T20:55:28 | 369,631,626 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 4,019 | r | ui.R |
#source("sections/ui_about.R", local = T)
#source("sections/ui_graphs.R", local = T)
source("sections/ui_maps.R", local = T)
source("sections/ui_about.R", local = T)
# meta tags https://rdrr.io/github/daattali/shinyalert/src/inst/examples/demo/ui.R
ui <- shinyUI(
ui <- function(req) {
fluidPage(theme = shinytheme("united"),
tags$head(
# includeHTML("google-analytics.html"),
tags$style(
type = "text/css",
# addmapane leflet
"img.leaflet-tile {
max-width: none !important;
max-height: none !important;
}",
"header {
border: 1px solid blue;
height: 150px;
display: flex; /* defines flexbox */
flex-direction: column; /* top to bottom */
justify-content: space-between; /* first item at start, last at end */
}",
"section {
border: 1px solid blue;
height: 150px;
display: flex; /* defines flexbox */
align-items: flex-end; /* bottom of the box */
}",
"body {padding-top: 70px;}",
# responsive images
"img {max-width: 100%; width: 100%; height: auto}",
# sliders color toate 3 variables
".js-irs-0 .irs-single, .js-irs-0 .irs-bar-edge, .js-irs-0 .irs-bar {background: #E95420; border-color: #E95420;}",
".js-irs-1 .irs-to,.js-irs-1 .irs-from , .js-irs-1 .irs-bar-edge, .js-irs-1 .irs-bar {background: #E95420; border-color: #E95420;}",
".js-irs-2 .irs-to,.js-irs-2 .irs-from , .js-irs-2 .irs-bar-edge, .js-irs-2 .irs-bar {background: #E95420; border-color: #E95420;}",
# sliders color toate 3 indicators
".js-irs-3 .irs-single, .js-irs-3 .irs-bar-edge, .js-irs-3 .irs-bar {background: #E95420; border-color: #E95420;}",
".js-irs-4 .irs-to,.js-irs-4 .irs-from , .js-irs-4 .irs-bar-edge, .js-irs-4 .irs-bar {background: #E95420; border-color: #E95420;}",
".js-irs-5 .irs-to,.js-irs-5 .irs-from , .js-irs-5 .irs-bar-edge, .js-irs-5 .irs-bar {background: #E95420; border-color: #E95420;}",
# inaltime navbaer
#'.navbar-brand{display:none;}'
#'
)
),
useShinyjs(),
navbarPage("RoCliB data explorer",
# tags$head(
# tags$style(HTML(
# ' .navbar-nav>li>a {
# padding-top: 5px;
# padding-bottom: 5px;
#
# }',
# '.navbar {min-height:5px !important;}'
# ))
# ),
collapsible = T, fluid = T, id = "tabs", position = "fixed-top",
selected = "#about",
# Statistics & Facts ------------------------------------------------------
#ui_graphs
# maps ------------------------------------------------------
ui_maps,
# NO2 Analysis----------------------------------------------------------
# no2_ui,
# About -------------------------------------------------------------------
about_ui
)
)
}
)
|
94d6c9aa3b2fc26c5d7b487688a164a31e303fbe | 29585dff702209dd446c0ab52ceea046c58e384e | /mreg/R/randfn.R | cdf1bf29942c687d9bb51481c01edeaddbb24a05 | [] | no_license | ingted/R-Examples | 825440ce468ce608c4d73e2af4c0a0213b81c0fe | d0917dbaf698cb8bc0789db0c3ab07453016eab9 | refs/heads/master | 2020-04-14T12:29:22.336088 | 2016-07-21T14:01:14 | 2016-07-21T14:01:14 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 277 | r | randfn.R | "randfn" <-
function(n, family, ...){
args <- list(...)
switch(family,
negbin= rnbinom(n, size=exp(args$size), mu=args$mu),
poisson=rpois(n, lambda=args$mu),
geometric=rgeom(n, prob= args$mu),
binom=rbinom(n, size=args$size, prob=args$mu)
)
}
|
15352ac293acd072e85c6c3c5ba61f38721b1812 | 8d207dbc1b45bee06135ed900eba7357b40c9b72 | /NBA Analysis.R | 085e66d2d6eb84786ba6ec7f852c6a5be248be6d | [] | no_license | ericborn/NBA-analysis | 12a18e95f1b9d86d6c4c5cf2ca086b16a23a1912 | 43c39e80fb5b80380000880348d66f3e17692348 | refs/heads/master | 2020-08-27T11:11:02.608035 | 2019-10-31T17:26:26 | 2019-10-31T17:26:26 | 217,346,121 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 18,048 | r | NBA Analysis.R | # Eric Born
# CS688 Final Project
# 2003-2004 NBA Analysis
library('XML')
library('rvest')
library('purrr')
library('plotly')
library('stringi')
library('googleVis')
library('SportsAnalytics')
# a)
# The 2003-2004 season of the NBA is being used as the dataset
######## b)
# pull down 2003-04 season stats
NBA.Stats <- fetch_NBAPlayerStatistics(season = "03-04", what = c("",".Home", ".Away"))
# clean-up 3 rows. Team GOL should be CLE, NO should be LAL
NBA.Stats[NBA.Stats$Team == 'GOL',]$Team <- 'CLE'
NBA.Stats[NBA.Stats$Team == 'NO',]$Team <- 'LAL'
# add new column which is the total points from field goals
NBA.Stats$twofg <- NBA.Stats$FieldGoalsMade - NBA.Stats$ThreesMade
NBA.Stats$twopts <- NBA.Stats$twofg * 2
NBA.Stats$threepts <- NBA.Stats$ThreesMade * 3
#NBA.Stats$relTotal <- NBA.Stats$FGpoints + NBA.Stats$threepoints + NBA.Stats$FreeThrowsMade
# output stats
# head(NBA.Stats)
# Total unique teams, players, max minutes, total points, total rebounds, total blocks
full.stats <- data.frame('Measure' = c('Unique teams', 'Unique players', 'Average minutes',
'Points', 'Rebounds', 'Blocks'),
'Total' = c(length(unique(NBA.Stats$Team)),
length(unique(NBA.Stats$Name)),
round(mean(NBA.Stats$TotalMinutesPlayed)),
sum(NBA.Stats$TotalPoints),
sum(NBA.Stats$TotalRebounds),
sum(NBA.Stats$Blocks)))
# reset factors to order by Measure column
full.stats$Measure <- factor(full.stats$Measure,
levels = c(as.character(full.stats$Measure)))
# Convert factors to character
full.stats$Measure <- as.character(full.stats$Measure)
# create table for NBA stats
nba.stat.table <- plot_ly(
type = 'table',
height = 225,
width = 500,
header = list(
values = c('Measure', 'Total'),
line = list(width = 1, color = 'black'),
fill = list(color = c('#1f77b4', '#1f77b4')),
font = list(famile = 'Arial', size = 14, color = 'white')
),
cells = list(
values = rbind(full.stats$Measure, full.stats$Total),
align = c('center'),
line = list(width = 1, color = 'black')
))
# Output table
nba.stat.table
####### c)
wolves <- NBA.Stats[NBA.Stats$Team == 'MIN',]
# Highest Total Points
points <- head(wolves[order(wolves$TotalPoints, decreasing = TRUE),c(2,21)], n=3)
# Highest Blocks
blocks <- head(wolves[order(wolves$Blocks, decreasing = TRUE),c(2,18)], n=3)
# Highest Rebounds
rebounds <- head(wolves[order(wolves$TotalRebounds, decreasing = TRUE),c(2,14)], n=3)
# create df for basic stats
basic.stats <- data.frame("Player" = c(points[[1]][1], points[[1]][2], points[[1]][3],
rebounds[[1]][1], rebounds[[1]][2], rebounds[[1]][3],
blocks[[1]][1], blocks[[1]][2], blocks[[1]][3]),
"Stat" = c('Points', 'Points', 'Points',
'Rebounds', 'Rebounds', 'Rebounds',
'Blocks','Blocks','Blocks'),
'Total' = c(points[[2]][1], points[[2]][2], points[[2]][3],
rebounds[[2]][1], rebounds[[2]][2], rebounds[[2]][3],
blocks[[2]][1], blocks[[2]][2], blocks[[2]][3]))
# Convert factors to character
basic.stats$Player <- as.character(basic.stats$Player)
# Convert factors to character
basic.stats$Stat <- as.character(basic.stats$Stat)
# create table for top 3 wolves players
stat.table <- plot_ly(
type = 'table',
height = 275,
width = 700,
header = list(
values = c('Player', 'Stat', 'Total'),
line = list(width = 1, color = 'black'),
fill = list(color = c('#1f77b4', '#1f77b4')),
font = list(famile = 'Arial', size = 14, color = 'white')
),
cells = list(
values = rbind(basic.stats$Player, basic.stats$Stat, basic.stats$Total),
align = c('center'),
line = list(width = 1, color = 'black')
))
# Output table
stat.table
###### d)
# top 5 teams for the 03-04 season
season.url <- 'https://www.landofbasketball.com/yearbyyear/2003_2004_standings.htm'
# read the html
webpage <- read_html(season.url)
# create var to hold wins/losses for each conference
mid.wins <- c(0)
mid.loss <- c(0)
pac.wins <- c(0)
pac.loss <- c(0)
atl.wins <- c(0)
atl.loss <- c(0)
cen.wins <- c(0)
cen.loss <- c(0)
# midwest div 7 teams
# loop through the columns grabbing each win and loss
for (k in 2:8){
mid.wins[[k]] <- webpage %>% html_nodes("table") %>% .[4] %>%
html_nodes("tr") %>% .[k] %>% html_nodes("td") %>% .[3] %>% html_text()
}
for (k in 2:8){
mid.loss[[k]] <- webpage %>% html_nodes("table") %>% .[4] %>%
html_nodes("tr") %>% .[k] %>% html_nodes("td") %>% .[4] %>% html_text()
}
# pac div 7 teams
# loop through the columns grabbing each win and loss
for (k in 2:8){
pac.wins[[k]] <- webpage %>% html_nodes("table") %>% .[5] %>%
html_nodes("tr") %>% .[k] %>% html_nodes("td") %>% .[3] %>% html_text()
}
for (k in 2:8){
pac.loss[[k]] <- webpage %>% html_nodes("table") %>% .[5] %>%
html_nodes("tr") %>% .[k] %>% html_nodes("td") %>% .[4] %>% html_text()
}
# atl div 7 teams
# loop through the columns grabbing each win and loss
for (k in 2:8){
atl.wins[[k]] <- webpage %>% html_nodes("table") %>% .[6] %>%
html_nodes("tr") %>% .[k] %>% html_nodes("td") %>% .[3] %>% html_text()
}
for (k in 2:8){
atl.loss[[k]] <- webpage %>% html_nodes("table") %>% .[6] %>%
html_nodes("tr") %>% .[k] %>% html_nodes("td") %>% .[4] %>% html_text()
}
# cen div 8 teams
# loop through the columns grabbing each win and loss
for (k in 2:9){
cen.wins[[k]] <- webpage %>% html_nodes("table") %>% .[7] %>%
html_nodes("tr") %>% .[k] %>% html_nodes("td") %>% .[3] %>% html_text()
}
for (k in 2:9){
cen.loss[[k]] <- webpage %>% html_nodes("table") %>% .[7] %>%
html_nodes("tr") %>% .[k] %>% html_nodes("td") %>% .[4] %>% html_text()
}
# drop the 1st index which is an NA
mid.wins <- mid.wins[-1]
mid.loss <- mid.loss[-1]
pac.wins <- pac.wins[-1]
pac.loss <- pac.loss[-1]
atl.wins <- atl.wins[-1]
atl.loss <- atl.loss[-1]
cen.wins <- cen.wins[-1]
cen.loss <- cen.loss[-1]
# team names by conference and division
western <- webpage %>% html_nodes("table") %>% .[1] %>% html_nodes("a") %>% html_text()
eastern <- webpage %>% html_nodes("table") %>% .[2] %>% html_nodes("a") %>% html_text()
midwest <- webpage %>% html_nodes("table") %>% .[4] %>% html_nodes("a") %>% html_text()
pacific <- webpage %>% html_nodes("table") %>% .[5] %>% html_nodes("a") %>% html_text()
atlantic <- webpage %>% html_nodes("table") %>% .[6] %>% html_nodes("a") %>% html_text()
central <- webpage %>% html_nodes("table") %>% .[7] %>% html_nodes("a") %>% html_text()
teams <- c(midwest, pacific, atlantic, central)
# Create dataframe from win/loss data
teams.df = data.frame(Team=teams,
Conference=c(rep('Western',length(western)),
rep('Eastern',length(eastern))),
Division=c(rep('Midwest', length(midwest)),
rep('Pacific', length(pacific)),
rep('Atlantic', length(atlantic)),
rep('Central', length(central))),
Win=c(mid.wins, pac.wins, atl.wins, cen.wins),
Loss=c(mid.loss,pac.loss,atl.loss,cen.loss))
# reset factors to order by Team column
teams.df$Team <- factor(teams.df$Team,
levels = c(as.character(teams.df$Team)))
# Convert factors to character
teams.df$Team <- as.character(teams.df$Team)
# Convert factors to character
teams.df$Conference <- as.character(teams.df$Conference)
# Convert factors to character
teams.df$Division <- as.character(teams.df$Division)
# Convert factors to character
teams.df$Win <- as.character(teams.df$Win)
# Convert factors to character
teams.df$Loss <- as.character(teams.df$Loss)
# order by wins
teams.df <- teams.df[order(teams.df$Win, decreasing = TRUE),]
# grab just top 5 teams by wins
teams.df.five <- head(teams.df[order(teams.df$Win, decreasing = TRUE),], n=5)
# create table for all nba teams with their conference, div, win/loss
full.record.table <- plot_ly(
type = 'table',
height = 800,
columnwidth = c(40, 30, 30, 15, 15),
header = list(
values = c('Team', 'Conference', 'Division', 'Win', 'Loss'),
line = list(width = 1, color = 'black'),
fill = list(color = c('#1f77b4', '#1f77b4')),
font = list(famile = 'Arial', size = 14, color = 'white')
),
cells = list(
values = rbind(teams.df$Team, teams.df$Conference, teams.df$Division,
teams.df$Win, teams.df$Loss),
align = c('center'),
line = list(width = 1, color = 'black')
))
# Output table
full.record.table
# create table for top 5 nba teams
top.record.table <- plot_ly(
type = 'table',
height = 200,
columnwidth = c(40, 30, 30, 15, 15),
header = list(
values = c('Team', 'Conference', 'Division', 'Win', 'Loss'),
line = list(width = 1, color = 'black'),
fill = list(color = c('#1f77b4', '#1f77b4')),
font = list(famile = 'Arial', size = 14, color = 'white')
),
cells = list(
values = rbind(teams.df.five$Team, teams.df.five$Conference,
teams.df.five$Division, teams.df.five$Win,
teams.df.five$Loss),
align = c('center'),
line = list(width = 1, color = 'black')
))
# Output table
top.record.table
####
# store team point totals for each category
# used in multiple plots further down
team.ft <- aggregate(FreeThrowsMade ~ Team, data = NBA.Stats, FUN=sum)
team.twopt <- aggregate(twopts ~ Team, data = NBA.Stats, FUN=sum)
team.threepts <- aggregate(threepts ~ Team, data = NBA.Stats, FUN=sum)
team.total <- aggregate(TotalPoints ~ Team, data = NBA.Stats, FUN=sum)
# turn point totals into a dataframe
all.points <- data.frame(Team=team.ft[1],
ft=team.ft[2],
twopt=team.twopt[2],
threepts=team.threepts[2],
total=team.total[2])
# reorder by total points
attach(all.points)
all.points <- all.points[order(-TotalPoints),]
detach(all.points)
# Reset rownames from 1 to n
rownames(all.points) <- 1:nrow(all.points)
# drop empty factor levels
all.points <- droplevels(all.points)
# reset factors to order by frequency decending
all.points$Team <- factor(all.points$Team,
levels = c(as.character(all.points$Team)))
####
######## e)
# 1)
# plot top 10 points per team
# gather total points per team
# only select top 10 teams by total points
top10.points <- all.points[1:10,c(1,5)]
# average points across all teams
avg.points <- round(mean(all.points$TotalPoints))
# setup plot
y <- list(title = "Total Points")
x <- list(title = 'Teams')
points.plot <- plot_ly(top10.points, x = ~Team, y= ~TotalPoints,
type='bar', color = ~Team)%>%
add_trace(y = avg.points, name = 'League Avg Points', type = 'scatter',
mode = 'lines', color = I('black'))%>%
layout(yaxis = y, title = "Top 10 Total Points per Team", xaxis = x)
# draw plot
points.plot
# 2)
# scorers breakdown for the wolves
# points from of 2pt Field Goals , Threes and Free Throws Made
# twopts, threepts, FreeThrowsMade
wolves.points <- wolves[c(2,27,28,11)]
# Create plot for all wolves players by types of points made
y <- list(title = "Total Points")
x <- list(title = 'Players')
wolves.plot <- plot_ly(wolves.points, x = ~Name, y = ~twopts, type = 'bar', name = 'Field Goals')%>%
add_trace(y = ~threepts, name = 'Threes' )%>%
add_trace(y = ~FreeThrowsMade, name = 'Free Throws' )%>%
layout(xaxis = x, yaxis = y, title = "Point Distribution of the Timberwolves", barmode = 'stack')
# draw plot
wolves.plot
# 3)
# Box plot
# store just the top 10 scoring team names
teams <- as.vector(top10.points$Team)
# pull players team and total points from top 10
top10.full <- NBA.Stats[with(NBA.Stats,Team %in% teams),c(3,21)]
# Reset rownames from 1 to n
rownames(top10.full) <- 1:nrow(top10.full)
# drop empty factor levels
top10.full <- droplevels(top10.full)
NBA.Stats[NBA.Stats$TotalPoints == 1557,c(2, 21)]
NBA.Stats[NBA.Stats$TotalPoints == 1439,c(2, 21)]
NBA.Stats[NBA.Stats$TotalPoints == 1776,c(2, 21)]
NBA.Stats[NBA.Stats$TotalPoints == 1964,c(2, 21)]
# Create boxplot based on top 10 highest scoring teams
y <- list(title = "Total Points")
x <- list(title = 'Team')
top.box <- plot_ly(top10.full, x = ~Team, y = ~TotalPoints, type = 'box', size = 2,
color = ~Team)%>%
layout(xaxis = x, yaxis = y, title = "Point distribution of top 10 teams")
# draw plot
top.box
# 4)
# top 10 scorers
# points from of 2pt Field Goals , Threes and Free Throws Made
# twopts, threepts, FreeThrowsMade
# players
players <- head(NBA.Stats[order(NBA.Stats$TotalPoints, decreasing = TRUE),c(2)], n=10)
# FieldGoalsMade, ThreesMade, FreeThrowsMade
player.points <- NBA.Stats[NBA.Stats$Name %in% players, c(2,27,28,11,21)]
attach(player.points)
player.points <- player.points[order(-TotalPoints),]
detach(player.points)
# Reset rownames from 1 to n
rownames(player.points) <- 1:nrow(player.points)
# drop empty factor levels
player.points <- droplevels(player.points)
# reset factors to order by frequency decending
player.points$Name <- factor(player.points$Name ,
levels = c(as.character(player.points$Name)))
# Create bar chart for top 10 scorers in the season
y <- list(title = "Total Points")
x <- list(title = 'Player')
players.plot <- plot_ly(player.points, x = ~Name, y = ~twopts, type = 'bar', name = 'Two pointers')%>%
add_trace(y = ~threepts, name = 'Threes' )%>%
add_trace(y = ~FreeThrowsMade, name = 'Free Throws' )%>%
layout(xaxis = x, yaxis = y, title = "Point Distribution of the Top 10 Players", barmode = 'stack')
# draw plot
players.plot
# 5)
# score breakdown per top 10 teams
# Limit to top 10
team.points <- all.points[1:10,]
# Reset rownames from 1 to n
rownames(team.points) <- 1:nrow(team.points)
# drop empty factor levels
team.points <- droplevels(team.points)
# reset factors to order by frequency decending
team.points$Team <- factor(team.points$Team ,
levels = c(as.character(team.points$Team)))
# Create bar plot for point distribution across top 10 teams
y <- list(title = "Total Points")
x <- list(title = 'Team')
team.point.plot <- plot_ly(team.points, x = ~Team, y = ~twopts, type = 'bar', name = 'Field Goals')%>%
add_trace(y = ~threepts, name = 'Threes' ) %>%
add_trace(y = ~FreeThrowsMade, name = 'Free Throws' ) %>%
layout(xaxis = x, yaxis = y, title = "Point Distribution of the Top 10 Teams", barmode = 'stack')
# draw plot
team.point.plot
# f)
# champ names
champ.url <- 'https://www.landofbasketball.com/championships/year_by_year.htm'
# read the html
champ.page <- read_html(champ.url)
# initalize vector
champ.names <- c(0)
# loop through page to get the last 20 NBA champs
for (k in 2:21){
champ.names[[k]] <- champ.page %>% html_nodes("table") %>% .[1] %>% html_nodes("tr") %>% .[k] %>%
html_nodes("a") %>% .[2] %>% html_text()
}
# drop index 1
champ.names <- champ.names[-1]
# Makes champion names unique
champ.names <- unique(champ.names)
# url for NBA team names and coordinates
city.url <- 'https://en.wikipedia.org/wiki/National_Basketball_Association'
# read html
city.page <- read_html(city.url)
# initalize empty list
champ.city <- list()
# grabs team and coords from first table
k = 3
# 4-18
for (i in 1:15){
# team name
champ.city[i] <- paste(city.page %>% html_nodes("table") %>% .[3] %>% html_nodes("tr") %>% .[k] %>%
html_nodes("td") %>% .[1] %>% html_text(),
# coords
city.page %>% html_nodes("table") %>% .[3] %>% html_nodes("tr") %>% .[k] %>%
html_nodes("td") %>% .[5] %>% html_nodes("span") %>% .[11] %>% html_text())
k <- k + 1
}
# grabs team and coords from second table
j = 19
# 19-34
for (i in 16:30){
# team name
champ.city[i] <- paste(city.page %>% html_nodes("table") %>% .[3] %>% html_nodes("tr") %>% .[j] %>%
html_nodes("td") %>% .[1] %>% html_text(),
# coords
city.page %>% html_nodes("table") %>% .[3] %>% html_nodes("tr") %>% .[j] %>%
html_nodes("td") %>% .[5] %>% html_nodes("span") %>% .[11] %>% html_text())
j <- j + 1
}
# split strings on \n
champ.split <- sapply(champ.city, function(x) strsplit(x, "\n"))
# initalize empty lists
names <- list()
coords <- list()
# creates separate lists from team names and coordinates
for (i in 1:length(champ.split)){
names[i] <- champ.split[[i]][1]
coords[i] <- champ.split[[i]][2]
}
# replace semi colon with colon
coords <- stri_replace_first_charclass(coords, "[;]", ":")
# remove leading space and space after colon
coords <- gsub(" ", "", coords)
# flatten list of names
names <- unlist(names)
# all teams and their coordinates as separate columns in a df
full.df <- data.frame(team = names, coords = coords)
# creates a df for just the champion teams
map.df <- data.frame(LatLong = full.df[full.df$team %in% champ.names,][2],
Tip = full.df[full.df$team %in% champ.names,][1])
# setup map
champMap <- gvisMap(map.df,
locationvar = 'coords',
tipvar = 'team',
options=list(showTip=TRUE,
showLine=TRUE,
enableScrollWheel=TRUE,
mapType='terrain',
useMapTypeControl=TRUE))
# draw map
plot(champMap)
|
f4ee02c3871120896da0b6c5748252f8fc90f1e2 | 7e3595925017a252e6a5c5ee48d4c7eb8fdcff93 | /ZYXUnaivelasso/man/print.las.Rd | c483aea4e084f89a41f5f3f13c2b18833abbc0b8 | [] | no_license | OliverXUZY/ZYXU_naivelasso_ | 9dd91071151d14ccc6378cf9939aac62ee468c58 | 45789f0fc4ff25d2d97b24939f95d97d34d6795b | refs/heads/master | 2020-04-09T04:14:42.534294 | 2018-12-02T05:23:21 | 2018-12-02T05:23:21 | 160,015,511 | 1 | 0 | null | null | null | null | UTF-8 | R | false | true | 412 | rd | print.las.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/print_lad.R
\name{print.las}
\alias{print.las}
\title{Print \deqn{coefficient of LASSO regression}}
\usage{
\method{print}{las}(obj, ...)
}
\arguments{
\item{obj}{the object you get from lasso function}
\item{...}{further arguments passed to or from other methods}
}
\description{
Calculate \deqn{LASSO regression}
}
|
eae249ed7b0d0575560004104376e3b5e5b8f736 | 99fa87a363c47c5304e101a1e7740e238aa01412 | /inst/article/simstudyintervals.R | 20910d3a8c8e5a84e8e1ab9a8197b54e986ccb93 | [] | no_license | elray1/PACwithDDM | f1d1cc6c249a687feea1dce4d45fe737a53772c4 | 01b6d323986ca05b2b6072318c0fe79d6dff7b31 | refs/heads/master | 2021-05-09T02:18:00.150153 | 2018-01-27T19:29:19 | 2018-01-27T19:29:19 | 119,192,480 | 1 | 0 | null | null | null | null | UTF-8 | R | false | false | 7,394 | r | simstudyintervals.R | <<fitSimStudyResultsLMEModel, cache = FALSE, echo = FALSE>>=
suppressMessages(suppressWarnings(library("nlme")))
suppressMessages(suppressWarnings(library("multcomp")))
# fit mixed effects model with a separate mean for each combination of
# data set, accelerometer location, response variable and fit method, random effect for subject, and
# variance specific to combination of subject, data set, response variable, and location
# results_fit <- lme(fixed = prop_correct ~ location * fit_method * data_set * response,
# random = ~ 1 | subject,
# # weights = varIdent(form = ~ 1 | subject * location),
# # weights = varIdent(form = ~ 1 | subject * location * data_set * response),
# weights = varIdent(form = ~ 1 | location * fit_method * data_set * response),
# data = combined_results_by_subject,
# control = lmeControl(maxIter = 500, msMaxIter = 500, niterEM = 250, msMaxEval = 2000))
#table(paste(combined_results_by_subject$location, combined_results_by_subject$fit_method, combined_results_by_subject$data_set, combined_results_by_subject$response, combined_results_by_subject$subject))
results_fit <- lme(fixed = prop_correct ~ obs_dist_complex * time_dep * fit_method,
random = ~ 1 | sim_ind,
# weights = varIdent(form = ~ 1 | subject * location),
# weights = varIdent(form = ~ 1 | subject * location * data_set * response),
weights = varIdent(form = ~ 1 | obs_dist_complex * time_dep * fit_method),
data = simStudyResults,
control = lmeControl(maxIter = 500, msMaxIter = 500, niterEM = 250, msMaxEval = 2000))
# assemble a data frame with estimates of relevant linear combinations of parameters and CIs.
# We want estimates for:
# - the mean for each combination of location and classification method
# - the difference in means between each pair of methods within location
# - the difference in means between each location within each method
unique_fit_methods <- as.character(unique(simStudyResults$fit_method))
unique_obs_dist_complex <- as.character(unique(simStudyResults$obs_dist_complex))
unique_time_dep <- as.character(unique(simStudyResults$time_dep))
num_fit_methods <- length(unique_fit_methods)
num_obs_dist_complex <- length(unique_obs_dist_complex)
num_time_dep <- length(unique_time_dep)
unique_fit_method_descriptors <- paste0("fit_method", sort(unique_fit_methods))
unique_obs_dist_complex_descriptors <- paste0("obs_dist_complex", sort(unique_obs_dist_complex))
unique_time_dep_descriptors <- paste0("time_dep", sort(unique_time_dep))
lc_df <- expand.grid(
fit_method = unique_fit_methods,
obs_dist_complex = unique_obs_dist_complex,
time_dep = unique_time_dep,
stringsAsFactors = FALSE)
lc_df$fit_method_descriptor <- paste0("fit_method", lc_df$fit_method)
lc_df$obs_dist_complex_descriptor <- paste0("obs_dist_complex", lc_df$obs_dist_complex)
lc_df$time_dep_descriptor <- paste0("time_dep", lc_df$time_dep)
lc_df$name <- apply(as.matrix(lc_df[, 1:4]), 1, paste, collapse = "-")
num_leading_cols <- ncol(lc_df)
coef_cols <- seq(
from = num_leading_cols + 1,
length = num_fit_methods * num_obs_dist_complex * num_time_dep
)
# corresponding indicator vector for each coefficient
coef_names <- names(fixef(results_fit))
unique_coef_name_component_descriptors <- unique(unlist(strsplit(coef_names, ":")))
intercept_fit_method <- unique_fit_method_descriptors[
!(unique_fit_method_descriptors %in% unique_coef_name_component_descriptors)]
intercept_obs_dist_complex <- unique_obs_dist_complex_descriptors[
!(unique_obs_dist_complex_descriptors %in% unique_coef_name_component_descriptors)]
intercept_time_dep <- unique_time_dep_descriptors[
!(unique_time_dep_descriptors %in% unique_coef_name_component_descriptors)]
for(coef_ind in seq(from = 1, to = length(coef_names))) {
split_name <- unlist(strsplit(coef_names[[coef_ind]], ":"))
if(!any(split_name %in% unique_fit_method_descriptors[unique_fit_method_descriptors != intercept_fit_method])) {
split_name <- c(split_name, unique_fit_method_descriptors)
}
if(!any(split_name %in% unique_obs_dist_complex_descriptors[unique_obs_dist_complex_descriptors != intercept_obs_dist_complex])) {
split_name <- c(split_name, unique_obs_dist_complex_descriptors)
}
if(!any(split_name %in% unique_time_dep_descriptors[unique_time_dep_descriptors != intercept_time_dep])) {
split_name <- c(split_name, unique_time_dep_descriptors)
}
lc_df[[paste0("coef", coef_ind)]] <- 0
lc_df[[paste0("coef", coef_ind)]][
lc_df$fit_method_descriptor %in% split_name &
lc_df$obs_dist_complex_descriptor %in% split_name &
lc_df$time_dep_descriptor %in% split_name] <- 1
}
## contrasts of
## (mean performance method 1) - (mean performance method 2) for all pairs of methods
## within obs_dist_complex and time_dep
rowind <- nrow(lc_df) # index of new row to add to lc_df
confint_rows <- c() # rows for which to compute confidence intervals
for(fit_method1_ind in seq(from = 1, to = length(unique_fit_methods) - 1)) {
for(fit_method2_ind in seq(from = fit_method1_ind + 1, to = length(unique_fit_methods))) {
fit_method1 <- unique_fit_methods[fit_method1_ind]
fit_method2 <- unique_fit_methods[fit_method2_ind]
for(obs_dist_complex_val in unique_obs_dist_complex) {
for(time_dep_val in unique_time_dep) {
rowind <- rowind + 1
confint_rows <- c(confint_rows, rowind)
m1_rowind <- which(lc_df$name == paste0(fit_method1, "-", obs_dist_complex_val, "-", time_dep_val, "-fit_method", fit_method1))
m2_rowind <- which(lc_df$name == paste0(fit_method2, "-", obs_dist_complex_val, "-", time_dep_val, "-fit_method", fit_method2))
lc_df[rowind, ] <- rep(NA, ncol(lc_df))
lc_df$name[rowind] <- paste0(fit_method1, "-", fit_method2, "-", obs_dist_complex_val, "-", time_dep_val)
lc_df$obs_dist_complex[rowind] <- obs_dist_complex_val
lc_df$time_dep[rowind] <- time_dep_val
lc_df[rowind, coef_cols] <- lc_df[m1_rowind, coef_cols] - lc_df[m2_rowind, coef_cols]
}
}
}
}
lc_df$name <- factor(lc_df$name, levels = lc_df$name)
K_mat <- as.matrix(lc_df[, coef_cols])
# get point estimates
lc_df$pt_est <- as.vector(K_mat %*% matrix(fixef(results_fit)))
# get familywise CIs
lc_df$fam_CI_lb <- NA
lc_df$fam_CI_ub <- NA
fam_CI_obj <- glht(results_fit, linfct = K_mat[confint_rows, ])
temp <- confint(fam_CI_obj)$confint
lc_df$fam_CI_lb[confint_rows] <- temp[, 2]
lc_df$fam_CI_ub[confint_rows] <- temp[, 3]
# get individual CIs
lc_df$ind_CI_lb <- NA
lc_df$ind_CI_ub <- NA
for(rowind in confint_rows) {
ind_CI_obj <- glht(results_fit, linfct = K_mat[rowind, , drop = FALSE])
temp <- confint(ind_CI_obj)$confint
lc_df$ind_CI_lb[rowind] <- temp[, 2]
lc_df$ind_CI_ub[rowind] <- temp[, 3]
}
summary_figure_df <-
lc_df[21:60, c("name", "obs_dist_complex", "time_dep", "pt_est", "fam_CI_lb", "fam_CI_ub", "ind_CI_lb", "ind_CI_ub")]
summary_figure_df$method_contrast <-
sapply(strsplit(as.character(summary_figure_df$name), "-", fixed = TRUE), function(comp) { paste(comp[1], "-", comp[2]) })
ggplot(data = summary_figure_df) +
geom_point(aes(x = method_contrast, y = pt_est)) +
geom_errorbar(aes(x = method_contrast, ymin = fam_CI_lb, ymax = fam_CI_ub)) +
facet_grid(time_dep ~ obs_dist_complex) +
xlab("Classification Model Pair") +
ylab("Difference in Proportion Correct") +
theme_bw() +
theme(axis.text.x=element_text(angle=90,hjust=1, vjust = 0.5))
|
43f87b127a22b0cef3e79bce8fd23bde665816f3 | 0500ba15e741ce1c84bfd397f0f3b43af8cb5ffb | /cran/paws.management/man/configservice_delete_resource_config.Rd | e7ad7a5778701c74247fbb407d25c589d1da0f58 | [
"Apache-2.0"
] | permissive | paws-r/paws | 196d42a2b9aca0e551a51ea5e6f34daca739591b | a689da2aee079391e100060524f6b973130f4e40 | refs/heads/main | 2023-08-18T00:33:48.538539 | 2023-08-09T09:31:24 | 2023-08-09T09:31:24 | 154,419,943 | 293 | 45 | NOASSERTION | 2023-09-14T15:31:32 | 2018-10-24T01:28:47 | R | UTF-8 | R | false | true | 869 | rd | configservice_delete_resource_config.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/configservice_operations.R
\name{configservice_delete_resource_config}
\alias{configservice_delete_resource_config}
\title{Records the configuration state for a custom resource that has been
deleted}
\usage{
configservice_delete_resource_config(ResourceType, ResourceId)
}
\arguments{
\item{ResourceType}{[required] The type of the resource.}
\item{ResourceId}{[required] Unique identifier of the resource.}
}
\description{
Records the configuration state for a custom resource that has been deleted. This API records a new ConfigurationItem with a ResourceDeleted status. You can retrieve the ConfigurationItems recorded for this resource in your Config History.
See \url{https://www.paws-r-sdk.com/docs/configservice_delete_resource_config/} for full documentation.
}
\keyword{internal}
|
dffbf2fdd8b0adc2ce7a0ecf675d1f45577e6173 | e4a1c496a3fe7e8f76d436313604db8fc041d92c | /ProgrammingAssignment_Week1/plot1.R | fc5570013b72698597ff884e7efefc86e34b6b99 | [] | no_license | iopetrid/ExploratoryStatistics | 0000c83ca334bbee328f18a44bd1e4e99574fb9e | aa0e20f28c4f1c0e9e10f78f65f20665923a4861 | refs/heads/master | 2020-04-06T09:30:22.884661 | 2018-11-13T12:30:22 | 2018-11-13T12:30:22 | 157,345,329 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 487 | r | plot1.R |
# Read all data and subset the desired data
all_data<-read.table("./household_power_consumption.txt",header=TRUE,sep=";",na.strings ="?")
desired_data<-subset(all_data,Date %in% c("1/2/2007","2/2/2007"))
desired_data$Date<-as.Date(desired_data$Date,"%d/%m/%Y")
# plot 1 and save to png
hist(desired_data$Global_active_power,col="red",xlab="Global Active Power (kilowatts)",ylab="Frequency",main="Global Active Power")
dev.copy(png,file="plot1.png", height=480, width=480)
dev.off()
|
188f238609c90998022b058a0fa49b66019d4380 | 2a7e77565c33e6b5d92ce6702b4a5fd96f80d7d0 | /fuzzedpackages/rotations/man/Q4.Rd | 8894c10bd5ac8e5657aa2d240f17e216837304f0 | [] | no_license | akhikolla/testpackages | 62ccaeed866e2194652b65e7360987b3b20df7e7 | 01259c3543febc89955ea5b79f3a08d3afe57e95 | refs/heads/master | 2023-02-18T03:50:28.288006 | 2021-01-18T13:23:32 | 2021-01-18T13:23:32 | 329,981,898 | 7 | 1 | null | null | null | null | UTF-8 | R | false | true | 3,794 | rd | Q4.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/Q4-class.R
\docType{data}
\name{Q4}
\alias{Q4}
\alias{as.Q4}
\alias{as.Q4.default}
\alias{as.Q4.SO3}
\alias{as.Q4.Q4}
\alias{as.Q4.data.frame}
\alias{is.Q4}
\alias{id.Q4}
\title{`Q4` class for storing rotation data as quaternions}
\format{
\code{id.Q4} is the identity rotation given by the matrix
\eqn{[1,0,0,0]^\top}{[1,0,0,0]'}.
An object of class \code{Q4} with 1 rows and 4 columns.
}
\usage{
as.Q4(x, ...)
\method{as.Q4}{default}(x, theta = NULL, ...)
\method{as.Q4}{SO3}(x, ...)
\method{as.Q4}{Q4}(x, ...)
\method{as.Q4}{data.frame}(x, ...)
is.Q4(x)
id.Q4
}
\arguments{
\item{x}{object to be coerced or tested}
\item{...}{additional arguments.}
\item{theta}{vector or single rotation angle; if \code{length(theta)==1}, the
same theta is used for all axes}
}
\value{
\item{as.Q4}{coerces its object into a Q4 type}
\item{is.Q4}{returns \code{TRUE} or \code{FALSE} depending on whether its
argument satisfies the conditions to be an quaternion; namely it must be
four-dimensional and of unit length}
}
\description{
Creates or tests for objects of class "Q4".
}
\details{
Construct a single or sample of rotations in 3-dimensions in quaternion form.
Several possible inputs for \code{x} are possible and they are differentiated
based on their class and dimension.
For \code{x} an n-by-3 matrix or a vector of length 3, the angle-axis
representation of rotations is utilized. More specifically, each quaternion
can be interpreted as a rotation of some reference frame about the axis
\eqn{U} (of unit length) through the angle \eqn{\theta}. For each axis and
angle the quaternion is formed through
\deqn{q=[cos(\theta/2),sin(\theta/2)U]^\top.}{q=[cos(theta/2),sin(theta/2)U]'.}
The object \code{x} is treated as if it has rows \eqn{U} and \code{theta} is
a vector or angles. If no angle is supplied then the length of each axis is
taken to be the angle of rotation theta.
For \code{x} an n-by-9 matrix of rotation matrices or an object of class
\code{"SO3"}, this function will return the quaternion equivalent of
\code{x}. See \code{\link{SO3}} or the vignette "rotations-intro" for more
details on rotation matrices.
For \code{x} an n-by-4 matrix, rows are treated as quaternions; rows that
aren't of unit length are made unit length while the rest are returned
untouched. A message is printed if any of the rows are not quaternions.
For \code{x} a \code{"data.frame"}, it is translated into a matrix of the
same dimension and the dimensionality of \code{x} is used to determine the
data type: angle-axis, quaternion or rotation (see above). As demonstrated
below, \code{is.Q4} may return \code{TRUE} for a data frame, but the
functions defined for objects of class \code{'Q4'} will not be called until
\code{as.Q4} has been used.
}
\examples{
# Pull off subject 1's wrist measurements
Subj1Wrist <- subset(drill, Subject == '1' & Joint == 'Wrist')
## The measurements are in columns 5:8
all(is.Q4(Subj1Wrist[,5:8])) #TRUE, even though Qs is a data.frame, the rows satisfy the
#conditions necessary to be quaternions BUT,
#S3 methods (e.g. 'mean' or 'plot') for objects of class
#'Q4' will not work until 'as.Q4' is used
Qs <- as.Q4(Subj1Wrist[,5:8]) #Coerce measurements into 'Q4' type using as.Q4.data.frame
all(is.Q4(Qs)) #TRUE
mean(Qs) #Estimate central orientation for subject 1's wrist, see ?mean.Q4
Rs <- as.SO3(Qs) #Coerce a 'Q4' object into rotation matrix format, see ?as.SO3
#Visualize the measurements, see ?plot.Q4 for more
\donttest{
plot(Qs, col = c(1, 2, 3))
}
}
\keyword{datasets}
|
df6870a769195f50d20bed78f886148668158d8d | c9e0c41b6e838d5d91c81cd1800e513ec53cd5ab | /man/gtkToolbarSetShowArrow.Rd | 53f432724924a19c4f01e5b32c5fbdeb7fe80e99 | [] | no_license | cran/RGtk2.10 | 3eb71086e637163c34e372c7c742922b079209e3 | 75aacd92d4b2db7d0942a3a6bc62105163b35c5e | refs/heads/master | 2021-01-22T23:26:26.975959 | 2007-05-05T00:00:00 | 2007-05-05T00:00:00 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 595 | rd | gtkToolbarSetShowArrow.Rd | \alias{gtkToolbarSetShowArrow}
\name{gtkToolbarSetShowArrow}
\title{gtkToolbarSetShowArrow}
\description{Sets whether to show an overflow menu when
\code{toolbar} doesn't have room for all items on it. If \code{TRUE},
items that there are not room are available through an
overflow menu.}
\usage{gtkToolbarSetShowArrow(object, show.arrow)}
\arguments{
\item{\code{object}}{[\code{\link{GtkToolbar}}] a \code{\link{GtkToolbar}}}
\item{\code{show.arrow}}{[logical] Whether to show an overflow menu}
}
\details{ Since 2.4}
\author{Derived by RGtkGen from GTK+ documentation}
\keyword{internal}
|
174030c5ecb3d1396b986db59a2588becab94158 | 8dd69e3acbf7981be3ced0f2db97e356ebe84804 | /R_Folder/Palencia_Hansel/test_shunt.R | d5ea2f83bdc8c48925ddec82afecdd38c2bf44ac | [] | no_license | creightond/Hydrocephalus_Payload | fc4c2e09b18ed772399748f88d7fcffc63e8eea5 | 0529037cabf8427b588e6cf51c619b9499487417 | refs/heads/master | 2022-06-20T19:10:08.982060 | 2020-05-13T00:25:31 | 2020-05-13T00:25:31 | 258,606,314 | 0 | 1 | null | null | null | null | UTF-8 | R | false | false | 2,749 | r | test_shunt.R | library(tidyverse)
dat <- read_csv("R_Folder/Data/DATALOG_FLIGHT.TXT")
dat <- dat %>%
select(`Sample Number`, `NR exptime (s)`, `X Acceleration (G)`, `Y Acceleration (G)`, `Z Acceleration (G)`, `Flight Altitude (ft)`)
dat <- map(dat, as.numeric)
dat <- data.frame(dat)
dat <- dat %>%
rowid_to_column()
# dat <- dat %>%
# filter(Flight.Altitude..ft. > 0,
# NR.exptime..s. > 0)
# dat %>%
# ggplot() +
# geom_point(aes(x = NR.exptime..s. , y = abs(dat$Flight.Altitude..ft. )))
#
# dat %>%
# ggplot() +
# geom_point(aes(x = NR.exptime..s./3600 , dat$X.Acceleration..G. ))
#
# dat %>%
# ggplot() +
# geom_point(aes(x = NR.exptime..s., dat$Y.Acceleration..G.))
#
# dat %>%
# ggplot() +
# geom_point(aes(x = NR.exptime..s., dat$Z.Acceleration..G.))
dat %>%
ggplot() +
geom_point(aes(x = Sample.Number, y = sqrt((dat$X.Acceleration..G.^2) + (dat$Y.Acceleration..G.^2) + (dat$Z.Acceleration..G.^2)))) +
scale_x_continuous(limits = c(6500, 17500))
dat %>%
ggplot() +
geom_point(aes(x = Sample.Number , y = dat$Flight.Altitude..ft., color = sqrt((dat$X.Acceleration..G.^2) + (dat$Y.Acceleration..G.^2) + (dat$Z.Acceleration..G.^2)))) +
scale_x_continuous(limits = c(6500, 17500))
# Something is wrong with this time sensor, it definitely isn't working how it's supposed to.
# I figured out the time isn't in the correct order for whatever reason, and there was obviously some dropped readings....
# It might be best to do a monte carlo A/R simulation to see if we can remove the bottom mess...
p1 <- dat %>%
filter(Sample.Number > 3500,
Sample.Number < 17500
#Flight.Altitude..ft. > 5000 --- This looks pretty good in cleaning misreads... I'm sure there is a good way to tell if something is misreading...
) %>%
select(NR.exptime..s., Flight.Altitude..ft.) %>%
distinct() %>%
ggplot() +
geom_point(aes(x = order(NR.exptime..s.), y = Flight.Altitude..ft., color = "Gradient of Shunt Flow")) +
scale_color_manual(values = "black") +
labs(x = "Time (s)", y = "Altitude (ft)", color = "Shunt Flow") +
theme_minimal()
p2 <- dat %>%
filter(rowid > 4500,
rowid < 21000,
Flight.Altitude..ft. > 60
#Flight.Altitude..ft. > 5000 --- This looks pretty good in cleaning misreads... I'm sure there is a good way to tell if something is misreading...
) %>%
select(Sample.Number , Flight.Altitude..ft.) %>%
distinct() %>%
ggplot() +
geom_point(aes(x = order(Sample.Number), y = Flight.Altitude..ft., color = "Gradient of Shunt Flow")) +
scale_color_manual(values = "black") +
labs(x = "Time (s)", y = "Altitude (ft)", color = "Shunt Flow") +
theme_minimal()
p1
p2
|
45735d4a8d0d2d0031a717c0ee350007cdb04ebc | 6a28ba69be875841ddc9e71ca6af5956110efcb2 | /Introductory_Statistics_by_Sheldon_M._Ross/CH6/EX6.7/Ex6_7.R | 643cd7c1131ebaaf70d4040870df4ad91c1c0ff1 | [] | permissive | FOSSEE/R_TBC_Uploads | 1ea929010b46babb1842b3efe0ed34be0deea3c0 | 8ab94daf80307aee399c246682cb79ccf6e9c282 | refs/heads/master | 2023-04-15T04:36:13.331525 | 2023-03-15T18:39:42 | 2023-03-15T18:39:42 | 212,745,783 | 0 | 3 | MIT | 2019-10-04T06:57:33 | 2019-10-04T05:57:19 | null | UTF-8 | R | false | false | 294 | r | Ex6_7.R | # Page No. 279
pa=2*(1-pnorm(1))
cat("P{|Z| > 1}=",signif(pa,digits=4))
pb=2*(1-pnorm(2))
cat("\nP{|Z| > 2}=",signif(pb, digits=4))
pc=2*(1-pnorm(3))
cat("\nP{|Z| > 3}=",signif(pc,digits=4))
cat("\nApproximation rule verified")
# The answer may slightly vary due to rounding off values. |
267195ea548f5efd99fdb67ad286cbd50db15162 | d80c94901adad9211f8cffb782d0e91e9860299b | /man/distsampOpen.Rd | 29f37e99bf93613d2f00244d739434f4769e243e | [] | no_license | rbchan/unmarked | b104daaa4d05178e5be74a509cc771ae5f246e55 | ac40eede793b0997209117080912a866a2ff18ae | refs/heads/master | 2023-08-16T22:44:39.138574 | 2023-08-11T20:21:52 | 2023-08-11T20:21:52 | 564,481 | 30 | 36 | null | 2023-08-11T20:21:53 | 2010-03-16T03:57:15 | R | UTF-8 | R | false | false | 10,275 | rd | distsampOpen.Rd | \name{distsampOpen}
\alias{distsampOpen}
\title{
Open population model for distance sampling data
}
\description{
Fit the model of Dail and Madsen (2011) and Hostetler and Chandler
(2015) with a distance sampling observation model (Sollmann et al. 2015).
}
\usage{
distsampOpen(lambdaformula, gammaformula, omegaformula, pformula,
data, keyfun=c("halfnorm", "exp", "hazard", "uniform"),
output=c("abund", "density"), unitsOut=c("ha", "kmsq"),
mixture=c("P", "NB", "ZIP"), K,
dynamics=c("constant", "autoreg", "notrend", "trend", "ricker", "gompertz"),
fix=c("none", "gamma", "omega"), immigration=FALSE, iotaformula = ~1,
starts, method="BFGS", se=TRUE, ...)
}
\arguments{
\item{lambdaformula}{Right-hand sided formula for initial abundance}
\item{gammaformula}{Right-hand sided formula for recruitment rate (when
dynamics is "constant", "autoreg", or "notrend") or population growth rate
(when dynamics is "trend", "ricker", or "gompertz")}
\item{omegaformula}{Right-hand sided formula for apparent survival probability
(when dynamics is "constant", "autoreg", or "notrend") or equilibrium
abundance (when dynamics is "ricker" or "gompertz")}
\item{pformula}{A right-hand side formula describing the detection
function covariates}
\item{data}{An object of class \code{\link{unmarkedFrameDSO}}}
\item{keyfun}{One of the following detection functions: "halfnorm", "hazard",
"exp", or "uniform"}
\item{output}{Model either "density" or "abund"}
\item{unitsOut}{Units of density. Either "ha" or "kmsq" for hectares and
square kilometers, respectively}
\item{mixture}{String specifying mixture: "P", "NB", or "ZIP" for
the Poisson, negative binomial, or zero-inflated Poisson
distributions respectively}
\item{K}{Integer defining upper bound of discrete integration. This
should be higher than the maximum observed count and high enough
that it does not affect the parameter estimates. However, the higher
the value the slower the computation}
\item{dynamics}{Character string describing the type of population
dynamics. "constant" indicates that there is no relationship between
omega and gamma. "autoreg" is an auto-regressive model in which
recruitment is modeled as gamma*N[i,t-1]. "notrend" model gamma as
lambda*(1-omega) such that there is no temporal trend. "trend" is
a model for exponential growth, N[i,t] = N[i,t-1]*gamma, where gamma
in this case is finite rate of increase (normally referred to as
lambda). "ricker" and "gompertz" are models for density-dependent
population growth. "ricker" is the Ricker-logistic model, N[i,t] =
N[i,t-1]*exp(gamma*(1-N[i,t-1]/omega)), where gamma is the maximum
instantaneous population growth rate (normally referred to as r) and
omega is the equilibrium abundance (normally referred to as K). "gompertz"
is a modified version of the Gompertz-logistic model, N[i,t] =
N[i,t-1]*exp(gamma*(1-log(N[i,t-1]+1)/log(omega+1))), where the
interpretations of gamma and omega are similar to in the Ricker model}
\item{fix}{If "omega", omega is fixed at 1. If "gamma", gamma is fixed at 0}
\item{immigration}{Logical specifying whether or not to include an immigration
term (iota) in population dynamics}
\item{iotaformula}{Right-hand sided formula for average number of immigrants
to a site per time step}
\item{starts}{Vector of starting values}
\item{method}{Optimization method used by \code{\link{optim}}}
\item{se}{Logical specifying whether or not to compute standard errors}
\item{\dots}{Additional arguments to optim, such as lower and upper bounds}
}
\details{
These models generalize distance sampling models (Buckland et al. 2001) by
relaxing the closure assumption (Dail and Madsen 2011, Hostetler and Chandler
2015, Sollmann et al. 2015).
The models include two or three additional parameters:
gamma, either the recruitment rate (births and immigrations), the
finite rate of increase, or the maximum instantaneous rate of increase;
omega, either the apparent survival rate (deaths and emigrations) or the
equilibrium abundance (carrying capacity); and iota, the number of immigrants
per site and year. Estimates of
population size at each time period can be derived from these
parameters, and thus so can trend estimates. Or, trend can be estimated
directly using dynamics="trend".
When immigration is set to FALSE (the default), iota is not modeled.
When immigration is set to TRUE and dynamics is set to "autoreg", the model
will separately estimate birth rate (gamma) and number of immigrants (iota).
When immigration is set to TRUE and dynamics is set to "trend", "ricker", or
"gompertz", the model will separately estimate local contributions to
population growth (gamma and omega) and number of immigrants (iota).
The latent abundance distribution, \eqn{f(N | \mathbf{\theta})}{f(N |
theta)} can be set as a Poisson, negative binomial, or zero-inflated
Poisson random
variable, depending on the setting of the \code{mixture} argument,
\code{mixture = "P"}, \code{mixture = "NB"}, \code{mixture = "ZIP"}
respectively. For the first two distributions, the mean of \eqn{N_i} is
\eqn{\lambda_i}{lambda_i}. If \eqn{N_i \sim NB}{N_i ~ NB}, then an
additional parameter, \eqn{\alpha}{alpha}, describes dispersion (lower
\eqn{\alpha}{alpha} implies higher variance). For the ZIP distribution,
the mean is \eqn{\lambda_i(1-\psi)}{lambda_i*(1-psi)}, where psi is the
zero-inflation parameter.
For "constant", "autoreg", or "notrend" dynamics, the latent abundance state
following the initial sampling period arises
from a
Markovian process in which survivors are modeled as \eqn{S_{it} \sim
Binomial(N_{it-1}, \omega_{it})}{S(i,t) ~ Binomial(N(i,t-1),
omega(i,t))}, and recruits
follow \eqn{G_{it} \sim Poisson(\gamma_{it})}{G(i,t) ~
Poisson(gamma(i,t))}.
Alternative population dynamics can be specified
using the \code{dynamics} and \code{immigration} arguments.
\eqn{\lambda_i}{lambda_i}, \eqn{\gamma_{it}}{gamma_it}, and
\eqn{\iota_{it}}{iota_it} are modeled
using the the log link.
\eqn{p_{ijt}}{p_ijt} is modeled using
the logit link.
\eqn{\omega_{it}}{omega_it} is either modeled using the logit link (for
"constant", "autoreg", or "notrend" dynamics) or the log link (for "ricker"
or "gompertz" dynamics). For "trend" dynamics, \eqn{\omega_{it}}{omega_it}
is not modeled.
For the distance sampling detection process, half-normal (\code{"halfnorm"}),
exponential (\code{"exp"}), hazard (\code{"hazard"}), and uniform
(\code{"uniform"}) key functions are available.
}
\value{An object of class unmarkedFitDSO}
\references{
Buckland, S.T., Anderson, D.R., Burnham, K.P., Laake, J.L., Borchers, D.L.
and Thomas, L. (2001) \emph{Introduction to Distance Sampling: Estimating
Abundance of Biological Populations}. Oxford University Press, Oxford, UK.
Dail, D. and L. Madsen (2011) Models for Estimating Abundance from
Repeated Counts of an Open Metapopulation. \emph{Biometrics}. 67: 577-587.
Hostetler, J. A. and R. B. Chandler (2015) Improved State-space Models for
Inference about Spatial and Temporal Variation in Abundance from Count Data.
\emph{Ecology} 96: 1713-1723.
Sollmann, R., Gardner, B., Chandler, R.B., Royle, J.A. and Sillett, T.S.
(2015) An open-population hierarchical distance sampling model.
\emph{Ecology} 96: 325-331.
}
\author{Richard Chandler, Jeff Hostetler, Andy Royle, Ken Kellner}
\note{
When gamma or omega are modeled using year-specific covariates, the
covariate data for the final year will be ignored; however,
they must be supplied.
If the time gap between primary periods is not constant, an M by T
matrix of integers should be supplied to \code{\link{unmarkedFrameDSO}}
using the \code{primaryPeriod} argument.
Secondary sampling periods are optional, but can greatly improve the
precision of the estimates.
Optimization may fail if the initial value of the intercept for the
detection parameter (sigma) is too small or large relative to transect width.
By default, this parameter is initialized at log(average band width).
You may have to adjust this starting value.
}
\section{Warning}{This function can be extremely slow, especially if
there are covariates of gamma or omega. Consider testing the timing on
a small subset of the data, perhaps with se=FALSE. Finding the lowest
value of K that does not affect estimates will also help with speed. }
\seealso{
\code{\link{distsamp}, \link{gdistsamp}, \link{unmarkedFrameDSO}}
}
\examples{
\dontrun{
#Generate some data
set.seed(123)
lambda=4; gamma=0.5; omega=0.8; sigma=25;
M=100; T=10; J=4
y <- array(NA, c(M, J, T))
N <- matrix(NA, M, T)
S <- G <- matrix(NA, M, T-1)
db <- c(0, 25, 50, 75, 100)
#Half-normal, line transect
g <- function(x, sig) exp(-x^2/(2*sig^2))
cp <- u <- a <- numeric(J)
L <- 1
a[1] <- L*db[2]
cp[1] <- integrate(g, db[1], db[2], sig=sigma)$value
for(j in 2:J) {
a[j] <- db[j+1] - sum(a[1:j])
cp[j] <- integrate(g, db[j], db[j+1], sig=sigma)$value
}
u <- a / sum(a)
cp <- cp / a * u
cp[j+1] <- 1-sum(cp)
for(i in 1:M) {
N[i,1] <- rpois(1, lambda)
y[i,1:J,1] <- rmultinom(1, N[i,1], cp)[1:J]
for(t in 1:(T-1)) {
S[i,t] <- rbinom(1, N[i,t], omega)
G[i,t] <- rpois(1, gamma)
N[i,t+1] <- S[i,t] + G[i,t]
y[i,1:J,t+1] <- rmultinom(1, N[i,t+1], cp)[1:J]
}
}
y <- matrix(y, M)
#Make a covariate
sc <- data.frame(x1 = rnorm(M))
umf <- unmarkedFrameDSO(y = y, siteCovs=sc, numPrimary=T, dist.breaks=db,
survey="line", unitsIn="m", tlength=rep(1, M))
(fit <- distsampOpen(~x1, ~1, ~1, ~1, data = umf, K=50, keyfun="halfnorm"))
#Compare to truth
cf <- coef(fit)
data.frame(model=c(exp(cf[1]), cf[2], exp(cf[3]), plogis(cf[4]), exp(cf[5])),
truth=c(lambda, 0, gamma, omega, sigma))
#Predict
head(predict(fit, type='lambda'))
#Check fit with parametric bootstrap
pb <- parboot(fit, nsims=15)
plot(pb)
# Empirical Bayes estimates of abundance for each site / year
re <- ranef(fit)
plot(re, layout=c(10,5), xlim=c(-1, 10))
}
}
\keyword{models}
|
bd232c7cfb715f461cb0665fa3f78c50beb20c79 | 86880f7b472955cc9928733a2077988e8ee6f847 | /figure/plot2.R | 26e735a74bedb7db2e095bddc069d3d8ea7b4558 | [] | no_license | cathetorres/ExData_Plotting1 | 84bb546c1f37b9eec8b8362b81da168decf1cee7 | 762514ddcd66f012210a798869a0449b36645d26 | refs/heads/master | 2021-01-22T09:47:44.273469 | 2015-04-11T16:20:23 | 2015-04-11T16:20:23 | 33,776,104 | 0 | 0 | null | 2015-04-11T13:09:59 | 2015-04-11T13:09:58 | null | UTF-8 | R | false | false | 638 | r | plot2.R | # Reading the data
df <- read.table("household_power_consumption.txt", header=T, sep=";", na.strings="?",
colClasses = c("character", "character", rep("numeric", 7)), comment.char="")
#Converting date
df$Date <- as.Date(df$Date, "%d/%m/%Y")
# Subsetting for date 2007-02-01 and 2007-02-02
df.subset <- df[df$Date == "2007-02-01" | df$Date== "2007-02-02", ]
# Plot 2
png(filename = "plot2.png", width=480, height=480)
plot(df.subset$Global_active_power, type="l", xlab= "", ylab="Global Active Power (kilowatts)", axes= F, frame= T)
axis(1, at= seq(0, 2880, by= 1440), labels= c("Thu", "Fri", "Sat"))
axis(2)
dev.off() |
52bba74ba73d54ac20f4729740e86ec8514eb4c4 | 9d8b743d802fb2a067ea4b1c12b44f4d9685418b | /man/plot-gdist-windowDistT.Rd | 5834e977c212c8a0332c41e5168b3df36ed986d3 | [] | no_license | cran/RcmdrPlugin.KMggplot2 | 24bee4662164a40a502101b4aef4e0aaa500e23d | a7397a49cf3ceab2bfc33fff8812e3c31b9e030d | refs/heads/master | 2021-01-14T02:35:35.657819 | 2019-09-17T06:10:02 | 2019-09-17T06:10:02 | 17,693,102 | 0 | 1 | null | null | null | null | UTF-8 | R | false | true | 357 | rd | plot-gdist-windowDistT.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/plot-gdist.r
\name{windowDistT}
\alias{windowDistT}
\title{Wrapper Function of t Distribution Plot Subclass}
\usage{
windowDistT()
}
\description{
\code{windowDistT} function is a wrapper function of \code{gdist} class for the R-commander menu bar.
}
\keyword{hplot}
|
5c21b386f4f6cbc140a9bfc7dcec1db19881a489 | 9719ea69f693adfddc62b27eaf948fc7b16f6ad0 | /R/add_dates.R | dcd104e8b8692a352b34182ee38b6e872478284b | [] | no_license | dbca-wa/wastdr | 49fe2fb1b8b1e518f6d38549ff12309de492a2ad | 5afb22d221d6d62f6482798d9108cca4c7736040 | refs/heads/master | 2022-11-18T01:00:41.039300 | 2022-11-16T08:32:12 | 2022-11-16T08:32:12 | 86,165,655 | 2 | 0 | null | null | null | null | UTF-8 | R | false | false | 2,620 | r | add_dates.R | #' Add turtle dates to a dataframe with datetime col `observation_start_time`.
#'
#' \lifecycle{stable}
#'
#' @param data a dataframe with datetime col `observation_start_time`, e.g. the
#' output of ODKC form "turtle track or nest", "predator or disturbance", or
#' "marine wildlife incident". If the date_col is plain text, it will be turned
#' into a tz-aware datetime, else it is expected to be POSIXct / POSIXt.
#' @param date_col (chr) The column name of the datetime to annotate.
#' Default: \code{"observation_start_time"}.
#' @param parse_date (lgl) Whether the date_col needs to be parsed from character
#' into a date format (TRUE, default) or already comes as a POSIXct/POSIXt.
#' @return The initial dataframe plus new columns
#' \itemize{
#' \item calendar_date_awst (POSIXct) The calendar date in GMT+08 (AWST) as
#' POSIXct, an ISO datetime in GMT+00.
#' \item calendar_date_awst_text (chr) The calendar date in GMT+08 (AWST) as
#' character to prevent spreadsheet programs from corrupting the values.
#' \item calendar_year (int) The calendar year in GMT+08 (AWST) as integer.
#' \item turtle_date (POSIXct) The turtle date,
#' see \code{\link{datetime_as_turtle_date}}.
#' \item season (int) The season, see \code{\link{datetime_as_season}}.
#' \item season_week (int) The season week,
#' see \code{\link{datetime_as_seasonweek}}.
#' \item iso_week (int) The season week,
#' see \code{\link{datetime_as_isoweek}}.
#' }
#' @family helpers
#' @export
add_dates <-
function(data,
date_col = "observation_start_time",
parse_date = TRUE) {
data %>%
{
if (parse_date == TRUE) {
dplyr::mutate(
.,
datetime = !!rlang::sym(date_col) %>%
httpdate_as_gmt08() %>%
lubridate::with_tz("Australia/Perth")
)
} else {
dplyr::mutate(., datetime = !!rlang::sym(date_col))
}
} %>%
dplyr::mutate(
calendar_date_awst = datetime %>%
lubridate::floor_date(unit = "day"), # %>% as.character(),
calendar_date_awst_text = datetime %>%
lubridate::floor_date(unit = "day") %>% as.character(),
calendar_year = datetime %>% lubridate::year(),
turtle_date = datetime %>% datetime_as_turtle_date(),
turtle_date_awst_text = turtle_date %>%
lubridate::floor_date(unit = "day") %>% as.character(),
season = datetime %>% datetime_as_season(),
season_week = datetime %>% datetime_as_seasonweek(),
iso_week = datetime %>% datetime_as_isoweek()
)
}
|
03ace20e536d9c8059d7eed0b5cf6cbf9138538b | acd7d1ed6175556193f2284c0933e675de9576ca | /log_log_pernambuco.R | 4783e5f7ea4bc554acb9c80bdf4af323fb6d0610 | [] | no_license | institutodegestao/covid19predicoes | a0eb61e4a83e1c232ef89ac6e73d6fa14a37ffb0 | f91199006bf27e369a012cc07176ff91dc61beb3 | refs/heads/master | 2022-11-09T21:01:26.231543 | 2020-06-21T23:58:26 | 2020-06-21T23:58:26 | 273,982,511 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,683 | r | log_log_pernambuco.R | fit_ll <- drm(totalCases ~ dia, fct = W1.4(),
data = pe_relatorio)
summary(fit_ll)
plot(fit_ll, log="", main = "Log logistic")
# x <- getMeanFunctions()
# LL.2 LL2.2 LL2.5 LL.3 LL.3u LL.4 LL.5 W1.2 W1.3 W1.4 AR.2
fit_ll_ob <- drm(deaths ~ dia, fct = LL.5(),
data = pe_relatorio)
summary(fit_ll_ob)
plot(fit_ll_ob, log="", main = "Log logistic")
pred_ll <- data.frame(predicao = ceil(predict(fit_ll, pred_dia)))
pred_ll$data <- seq.Date(as.Date('2020-03-12'), by = 'day', length.out = length(pred_dia$dia))
pred_ll_ob <- data.frame(predicaoOb = ceil(predict(fit_ll_ob, pred_dia)))
pred_ll_ob$data <- seq.Date(as.Date('2020-03-12'), by = 'day', length.out = length(pred_dia$dia))
pred_ll <- merge(pred_ll, pe_relatorio, by = 'data', all.x = T)
pred_ll <- merge(pred_ll, pred_ll_ob, by = 'data', all.x = T)
pred_ll$pred_obitos <- ceil(pred_ll$predicao * last(quadro_pernambuco$tx_obitos))
pred_ll$pred_uti <- ceil(pred_ll$predicao * last(quadro_pernambuco$tx_uti))
pred_ll <- pred_ll[,c('data', 'dia', 'totalCases', 'predicao', 'deaths', 'pred_obitos', 'pred_uti', 'predicaoOb')]
colnames(pred_ll)[c(3,5)] <- c('confirmados', 'obitos')
pred_ll$pred_dia <- pred_ll$predicao - Lag(pred_ll$predicao, +1)
pred_ll$pred_ob_dia <- pred_ll$predicaoOb - Lag(pred_ll$predicaoOb, +1)
base_pred <- subset(pred_ll, data == '2020-04-19')
idades$pred_obitos <- ceil(base_pred$predicao * idades$chance_obito * idades$propocao)
idades <- idades[, c('faixa_etaria', 'confirmados', 'obitos', 'propocao', 'chance_obito', 'pred_obitos')]
colnames(idades)[c(4,5)] <- c('proporcao', 'letalidade')
write.table(pred_ll, '../../covidpe/resultado/pred_ll.csv', sep = ';', row.names=FALSE) |
1f4b7f376dd5fabbb6ef5258148abc2c89b54c7e | 4d36492368e067bdc821b2ee8bc5a9d524458c9a | /man/processcheckR.Rd | 8ba62f11cab4303719c9aafce4b08b5338a7aa5c | [] | no_license | cran/processcheckR | 27e177bb799cb9ebfe4708ea56c9bb99cbd1685f | bb4e4523ae7b65f4f37adcf3eb1380735f8887a3 | refs/heads/master | 2022-10-15T01:29:09.022611 | 2022-10-03T08:40:08 | 2022-10-03T08:40:08 | 152,093,595 | 1 | 0 | null | null | null | null | UTF-8 | R | false | true | 298 | rd | processcheckR.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/processcheckR.R
\docType{package}
\name{processcheckR}
\alias{processcheckR}
\title{processcheckR - Check rules in event data}
\description{
Tools to check declarative rules in event logs.
}
\keyword{internal}
|
50326a46d4fe17a7282e2fbb8f6be7ad9a842f40 | b2f1be76cc51511dded3eb5c2d080f83b8bee71f | /man/mergeSubCluster.Rd | 2642ab7feea695bd0eb4a08c684b9f0b6b09fe72 | [] | no_license | basilkhuder/extendSC | 17ecbb001ba649c7b4cf6b2f0023be60b1a7d810 | 5e32181c088b0a6e8e64affc8f373cc90bc3cfbd | refs/heads/master | 2023-06-18T17:33:04.791354 | 2021-07-19T22:00:24 | 2021-07-19T22:00:24 | 243,655,379 | 3 | 1 | null | null | null | null | UTF-8 | R | false | true | 763 | rd | mergeSubCluster.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/mergeSubCluster.R
\name{mergeSubCluster}
\alias{mergeSubCluster}
\title{Merge a reclusted sub-sample back into main object}
\usage{
mergeSubCluster(seurat.obj, subcluster.obj, cluster.replace, annotation.name)
}
\arguments{
\item{seurat.obj}{A Seurat object.}
\item{subcluster.obj}{A Seurat sub-cluster object}
\item{annotation.name}{Name to store cluster annotations}
\item{cluster.repace}{Clusters to replace}
}
\value{
Merged seurat object
}
\description{
Merge a reclusted sub-sample back into main object
}
\examples{
mergedSubCluster(seurat.obj, subcluster.obj = seurat.sub.obj, cluster.replace = "T Cells", annotation.name = "Seurat_Assignment")
}
|
9a5bc2c0a6c42485f36a75a465bd83695056b5dd | cdfb90159c8162e80796a92ac63de0d37ea91478 | /man/home_run_contour.Rd | e74870b37e070a7e351341095b1cb447d489f375 | [] | no_license | bayesball/CalledStrike | 28168c684b2004733c11733905a62912dd70b7fc | 451438ace005564dc51abd53510d4efeffaf8a68 | refs/heads/master | 2022-06-07T20:44:59.341284 | 2022-03-21T13:14:32 | 2022-03-21T13:14:32 | 169,013,289 | 6 | 4 | null | null | null | null | UTF-8 | R | false | false | 565 | rd | home_run_contour.Rd | \name{home_run_contour}
\alias{home_run_contour}
\title{
Home Run Contour Plot
}
\description{
Constructs home run contour plot for a specific player
}
\usage{
home_run_contour(df, L = seq(0.04, 0.24, by = 0.04), title, NCOL = 2)
}
\arguments{
\item{df}{
data frame or list containing Statcast data
}
\item{L}{
values for the contour lines
}
\item{title}{
title of the graph
}
\item{NCOL}{
number of columns in multipanel display
}
}
\value{
Constructs a contour plot of the home run probability
}
\author{
Jim Albert
}
|
75d77d351cf8e495d687070ceb26d400acf9cb33 | 2a186ccb02ff9b304baa3a4ae13653bc9397990c | /data frame/loop break.R | da7d197decb2ade91dc4a0f56f1db373bc3b5c59 | [] | no_license | aigurus/nptel-Python_for_DS_and_Data_ScienceforEngg | 873ff50bfc9fe03e1de7970d5ff91626b5834973 | a0825d4b8158ab0c0292b0ce3534eaed1569453d | refs/heads/master | 2022-10-22T16:15:20.748793 | 2020-06-20T06:19:09 | 2020-06-20T06:19:09 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 96 | r | loop break.R | n=100
sum=0
for(i in seq(1,n,2)){
sum=sum+i
print(c(i,sum))
if(sum>20)
break
}
|
c29cde7517ba6318d88d08e776860327d06e63f8 | dbd043b4c25b321dbf4bdbb84f9072f0ee3975bc | /R/datasets.R | c5bb78627d6fb3c2b80be94150907a71821fd13f | [] | no_license | tylergiallanza/arulesViz | c6654b6832cc4781418aedea8afa4b0d1f7d743f | 451303bb506788d39729c97e2cc3b183af2f5562 | refs/heads/master | 2022-04-14T18:09:24.382289 | 2020-04-19T22:57:45 | 2020-04-19T22:57:45 | 114,668,835 | 1 | 0 | null | 2018-04-09T22:13:32 | 2017-12-18T17:26:02 | R | UTF-8 | R | false | false | 47,181 | r | datasets.R | library('devtools')
#install_github('ianjjohnson/arulesCBA')
#install('C:\\Users\\Tylergiallanza\\Downloads\\arulesCBA-master\\arulesCBA-master')
library(arulesCBA)
library(randomForest)
library(tensorflow)
library(caret)
count_na <- function(df) {
sapply(df, function(y) sum(length(which(is.na(y)))))
}
prepare_vote <- function() {
vote_data <- read.csv(url('https://archive.ics.uci.edu/ml/machine-learning-databases/voting-records/house-votes-84.data'),
header=FALSE,sep=',', na.strings = '?')
vote_data$cls <- factor(vote_data[,'V1']) #class variable
vote_data[,'V1'] <- NULL
vote_data <- discretizeDF.supervised('cls~.',vote_data)
#vote_data <- as(vote_data,'transactions')
vote_data
}
prepare_mush <- function() {
mush_data <- read.csv(url('https://archive.ics.uci.edu/ml/machine-learning-databases/mushroom/agaricus-lepiota.data'),
header=FALSE,sep=',', na.strings = '?')
mush_data$cls <- factor(mush_data[,'V1']) #class variable
mush_data[,'V1'] <- NULL
mush_data <- discretizeDF.supervised('cls~.',mush_data)
#vote_data <- as(vote_data,'transactions')
mush_data
}
prepare_cancer <- function() {
cancer_data <- read.csv(url('https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer/breast-cancer.data'),
header=FALSE,sep=',', na.strings = '?')
cancer_data$cls <- factor(cancer_data[,'V9']) #class variable
cancer_data[,'V9'] <- NULL
cancer_data <- discretizeDF.supervised('cls~.',cancer_data)
cancer_data
}
prepare_vote_params <- function() {
reg_params <- list(l1=0.005)
list(support=0.15,confidence=1,regularization="l1",learning_rate=0.05,epoch=50,regularization_weights=reg_params,deep=5L)
#supports in c(0.05, 0.1, 0.2, 0.25)
#confs in c(.5,.75,.9,1)
}
prepare_mush_params <- function() {
reg_params <- list(l1=0.005)
list(support=0.1,confidence=1,regularization="l1",learning_rate=0.05,epoch=50,regularization_weights=reg_params,
batch_size=128)
#support in c(0.2, 0.25, 0.3)
#confs in c(.5, .75, .9, 1)
}
run_inner_crossval <- function(formula, trans, cwar_params, crossval_index = 0) {
split_point <- round(0.9*length(trans))
train_trans <- trans[1:split_point]
test_trans <- trans[split_point:length(trans)]
accs <- list()
models <- list()
model_index <- 1
print("Running grid search.")
#for(support in c(0.05, 0.1, 0.2, 0.25)) {
#for(support in c(0.2)){#, 0.25, 0.3)){
for(support in c(0.15)) {
#for(confidence in c(.5, .75, .9, 1)) {
for(confidence in c(.5)) {
print(" Running grid iteration...")
temp_params <- cwar_params
temp_params$support <- support
temp_params$confidence <- confidence
model <- CWAR(formula, trans, temp_params, 0)
y_true <- transactions_to_labels(formula,test_trans)
y_pred <- predict(model, test_trans)
acc <- sum(y_true==y_pred)/length(y_true)
accs[[model_index]] <- acc
models[[model_index]] <- model
model_index <- model_index + 1
}
}
model_params <- unlist(lapply(models, function(x) x$params))
model_params <- list()
for(model_index in 1:length(models)) {
model_params[[model_index]] <- models[[model_index]]$params
}
save(accs,model_params,file=paste0('models-',crossval_index,'.RData'))
return(models[[which.max(accs)]])
}
find_rf_params <- function(formula, data) {
split_point <- round(0.9*length(data))
train_data <- data[1:split_point,]
test_data <- data[split_point:length(data),]
base_mtry <- floor(sqrt(ncol(train_data)))
best_acc <- 0
best_model <- NULL
for(ntree in c(500,1000,2000)) {
for(mtry in c(floor(base_mtry/2),base_mtry,base_mtry*2)) {
model <- randomForest(formula, train_data, ntree = ntree, mtry = mtry, na.action=na.roughfix)
y_pred <- predict(model, na.roughfix(test_data))
y_true <- transactions_to_labels(formula,as(test_data,'transactions'))
acc <- sum(y_true==y_pred)/length(y_true)
if(acc > best_acc) {
best_acc <- acc
best_model <- model
}
}
}
return(best_model)
}
run_crossval <- function(formula, data, cwar_params, crossval_index = 0, run_model = F, run_rf = F, run_cba = F, run_rcar = F) {
trans <- as(data, 'transactions')
test_length <- floor(0.1*length(trans))
test_start <- crossval_index*test_length
test_indices <- 1:test_length+test_start
train_data <- data[-test_indices,]
train_trans <- trans[-test_indices]
test_data <- data[test_indices,]
test_trans <- trans[test_indices]
#model <- CWAR(formula, trans, cwar_params, 1)
y_true <- transactions_to_labels(formula,test_trans)
return_model <- NULL
if(run_model) {
model <- run_inner_crossval(formula, train_trans, cwar_params, crossval_index)
return_model <- model
y_pred <- predict(model, test_trans)
plot(1:cwar_params$epoch,model$history$loss)
plot(1:cwar_params$epoch,model$history$accuracy)
plot(1:cwar_params$epoch,model$history$rules)
print('model results')
print(confusionMatrix(y_pred,y_true))
}
if(run_rf) {
rf_model <- find_rf_params(formula, train_data)
y_pred <- predict(rf_model, na.roughfix(test_data))
print('rf results')
print(confusionMatrix(y_pred,y_true))
print(rf_model)
}
if(run_cba) {
#supp <- model$support
#conf <- model$confidence
supp <- 0.2
conf <- 0.5
cba_model <- CBA(formula, train_data, support = supp, confidence = conf)
y_pred <- predict(cba_model, test_data)
print('cba results')
print(confusionMatrix(y_pred,y_true))
if(!run_model) {
return_model <- cba_model
}
}
if(run_rcar) {
supp <- 0.2
conf <- 0.5
rcar_model <- rcar(train_data, which(colnames(train_data)=='cls'), s= supp, c= conf, lambd=2*cwar_params$regularization_weights$l1)
print('rcar results')
y_pred <- factor(predict.rcar(rcar_model, test_data))
print(confusionMatrix(y_pred,y_true))
if(!run_model) {
return_model <- rcar_model
}
}
return(return_model)
}
if(F) {
#good
prepare_anneal <- function() {
anneal_data <- read.csv(url('https://archive.ics.uci.edu/ml/machine-learning-databases/annealing/anneal.data'),
header=FALSE,sep=',')
anneal_data[['V1']] <- NULL
anneal_data$V39 <- factor(anneal_data[,'V39']) #class variable
anneal_data <- discretizeDF.supervised('V39~.',anneal_data)
anneal_data
}
#good
prepare_austral <- function() {
austral_data <- read.csv(url('http://archive.ics.uci.edu/ml/machine-learning-databases/statlog/australian/australian.dat'),
header=FALSE,sep=' ')
austral_data$V15 <- factor(austral_data[,'V15']) #CLASS VARIABLE
austral_data <- discretizeDF.supervised('V15~.',austral_data)
austral_data
}
#good
prepare_auto <- function() {
auto_data <- read.csv(url('https://archive.ics.uci.edu/ml/machine-learning-databases/autos/imports-85.data'),
header=FALSE,sep=',',na.strings='?')
temp <- factor(auto_data[['V1']])
auto_data[['V2']] <- NULL
auto_data$V26 <- temp #class variable
auto_data <- discretizeDF.supervised('V26~.',auto_data)
auto_data
}
#good
prepare_bc <- function() {
bc_data <- read.csv(url('https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/breast-cancer-wisconsin.data'),header=FALSE)
bc_data$V1 <- NULL
bc_data[,'V2'] <- factor(bc_data[,'V2'])
bc_data[,'V3'] <- factor(bc_data[,'V3'])
bc_data[,'V4'] <- factor(bc_data[,'V4'])
bc_data[,'V5'] <- factor(bc_data[,'V5'])
bc_data[,'V6'] <- factor(bc_data[,'V6'])
bc_data[,'V7'] <- factor(bc_data[,'V7'])
bc_data[,'V8'] <- factor(bc_data[,'V8'])
bc_data[,'V9'] <- factor(bc_data[,'V9'])
bc_data[,'V10'] <- factor(bc_data[,'V10'])
bc_data[,'V11'] <- factor(bc_data[,'V11'])
bc_data
}
#good
prepare_crx <- function() {
crx_data <- read.csv(url('https://archive.ics.uci.edu/ml/machine-learning-databases/credit-screening/crx.data'),header=FALSE,
na.strings='?')
crx_data[,'V16'] <- factor(crx_data[,'V16']) #CLASS VARIABLE
crx_data <- discretizeDF.supervised('V16~.',crx_data)
crx_data
}
#good
prepare_cleve <- function() {
cleve_data <- read.csv(url('https://archive.ics.uci.edu/ml/machine-learning-databases/heart-disease/processed.cleveland.data'),
header=F,sep=',')
change_indices <- c(which(cleve_data$V14!='0'))
cleve_data[change_indices,'V14'] <- 1
cleve_data[,'V14'] <- factor(cleve_data[,'V14'])
cleve_data <- discretizeDF.supervised('V14~.',cleve_data)
cleve_data
}
#good
prepare_german <- function() {
german_data <- read.csv(url('https://archive.ics.uci.edu/ml/machine-learning-databases/statlog/german/german.data'),header=FALSE,sep=' ')
german_data$V21 <- factor(german_data[,'V21']) #Class variable
german_data <- discretizeDF.supervised('V21~.',german_data)
german_data
}
#good
prepare_glass <- function() {
glass_data <- read.csv(url('https://archive.ics.uci.edu/ml/machine-learning-databases/glass/glass.data'),header=FALSE,sep=',')
glass_data$V1 <- NULL
glass_data$V11 <- factor(glass_data[,'V11']) #Class variable
glass_data <- discretizeDF.supervised('V11~.',glass_data)
glass_data
}
#good
prepare_heart <- function() {
heart_data <- read.table(url('https://archive.ics.uci.edu/ml/machine-learning-databases/statlog/heart/heart.dat'),
sep=' ',header=FALSE)
heart_data[,'V14'] <- factor(heart_data[,'V14'])
heart_data <- discretizeDF.supervised('V14~.',heart_data)
heart_data
}
#good
prepare_hepatic <- function() {
hepatic_data <- read.csv(url('https://archive.ics.uci.edu/ml/machine-learning-databases/hepatitis/hepatitis.data'),sep=',',header=FALSE)
temp <- factor(hepatic_data[,'V1'])
hepatic_data$V1 <- hepatic_data[,'V20']
hepatic_data$V20 <- temp
hepatic_data <- discretizeDF.supervised('V20~.',hepatic_data)
hepatic_data
}
#good
prepare_horse <- function() {
#horse_data <- read.table('~/Dropbox/School/CSE5393/sgd/horse.csv',
# sep=',',header=FALSE)
horse_data <- read.table('D:\\Dropbox\\School\\CSE5393\\sgd\\horse.csv',
sep=',',header=FALSE,na.strings='?')
horse_data[,'V3'] <- NULL
horse_data[,'V24'] <- factor(horse_data[,'V24'])
horse_data <- discretizeDF.supervised('V24~.',horse_data)
horse_data
}
#good
prepare_iono <- function() {
iono_data <- read.table(url('https://archive.ics.uci.edu/ml/machine-learning-databases/ionosphere/ionosphere.data'),
sep=',',header=FALSE)
iono_data[,'V35'] <- factor(iono_data[,'V35'])
iono_data <- discretizeDF.supervised('V35~.',iono_data)
iono_data
}
#good
prepare_iris <- function() {
iris_data <- read.table(url('https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'),
sep=',',header=FALSE)
iris_data[,'V5'] <- factor(iris_data[,'V5'])
iris_data <- discretizeDF.supervised('V5~.',iris_data)
iris_data
}
#good
prepare_labor <- function() {
labor_data <- read.csv('~/Dropbox/School/CSE5393/sgd/labor.csv',sep=',',header=FALSE,na.strings='?')
labor_data$V17 <- factor(labor_data$V17)
labor_data <- discretizeDF.supervised('V17~.',labor_data)
labor_data
}
#good
prepare_led7 <- function() {
led7_data <- read.table('~/Dropbox/School/CSE5393/sgd/led7.csv',
sep=',',header=FALSE)
led7_data[,'V1'] <- factor(led7_data[,'V1'])
led7_data[,'V2'] <- factor(led7_data[,'V2'])
led7_data[,'V3'] <- factor(led7_data[,'V3'])
led7_data[,'V4'] <- factor(led7_data[,'V4'])
led7_data[,'V5'] <- factor(led7_data[,'V5'])
led7_data[,'V6'] <- factor(led7_data[,'V6'])
led7_data[,'V7'] <- factor(led7_data[,'V7'])
led7_data[,'V8'] <- factor(led7_data[,'V8']) #Class variable
led7_data
}
#good
prepare_lymph <- function() {
lymph_data <- read.table(url('https://archive.ics.uci.edu/ml/machine-learning-databases/lymphography/lymphography.data'),
sep=',',header=FALSE)
temp <- factor(lymph_data[,'V1'])
lymph_data[,'V1'] <- lymph_data[,'V19']
lymph_data[,'V19'] <- temp #class variable
lymph_data <- discretizeDF.supervised('V19~.',lymph_data)
lymph_data
}
#good
prepare_pima <- function() {
pima_data <- read.csv(url('https://gist.githubusercontent.com/ktisha/c21e73a1bd1700294ef790c56c8aec1f/raw/819b69b5736821ccee93d05b51de0510bea00294/pima-indians-diabetes.csv'),
sep=',',header=FALSE,skip=9)
pima_data[,'V9'] <- factor(pima_data[,'V9']) #class variable
pima_data <- discretizeDF.supervised('V9~.',pima_data)
pima_data
}
#good
prepare_sick <- function() {
sick_data <- read.table(url('https://archive.ics.uci.edu/ml/machine-learning-databases/thyroid-disease/sick.data'),
sep=',',header=FALSE)
sick_data[,'V30'] <- as.character(levels(sick_data[,'V30']))[sick_data[,'V30']]
class_labels <- unlist(strsplit(sick_data[,'V30'],"\\."))[1:length(sick_data[,'V30'])*2-1]
sick_data[,'V30'] <- factor(class_labels)
sick_data <- discretizeDF.supervised('V30~.',sick_data)
sick_data
}
#good
prepare_sonar <- function() {
sonar_data <- read.table(url('http://archive.ics.uci.edu/ml/machine-learning-databases/undocumented/connectionist-bench/sonar/sonar.all-data'),
sep=',',header=FALSE)
sonar_data[,'V61'] <- factor(sonar_data[,'V61']) #class variable
sonar_data <- discretizeDF.supervised('V61~.',sonar_data)
sonar_data
}
#good
prepare_tic <- function() {
tic_data <- read.table(url('https://archive.ics.uci.edu/ml/machine-learning-databases/tic-tac-toe/tic-tac-toe.data'),
sep=',',header=FALSE)
tic_data[,'V1'] <- factor(tic_data[,'V1'])
tic_data[,'V2'] <- factor(tic_data[,'V2'])
tic_data[,'V3'] <- factor(tic_data[,'V3'])
tic_data[,'V4'] <- factor(tic_data[,'V4'])
tic_data[,'V5'] <- factor(tic_data[,'V5'])
tic_data[,'V6'] <- factor(tic_data[,'V6'])
tic_data[,'V7'] <- factor(tic_data[,'V7'])
tic_data[,'V8'] <- factor(tic_data[,'V8'])
tic_data[,'V9'] <- factor(tic_data[,'V9'])
tic_data[,'V10'] <- factor(tic_data[,'V10'])
tic_data
}
#good
prepare_wine <- function() {
wine_data <- read.table(url('https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data'),
sep=',',header=FALSE)
temp <- factor(wine_data[,'V1'])
wine_data[,'V1'] <- wine_data[,'V13']
wine_data[,'V13'] <- temp
wine_data <- discretizeDF.supervised('V13~.',wine_data)
wine_data
}
#good
prepare_waveform <- function() {
waveform_data <- read.table('~/Dropbox/School/CSE5393/sgd/waveform.data',sep=',',header=F,na.strings='?')
waveform_data$V22 <- factor(waveform_data$V22)
waveform_data <- discretizeDF.supervised('V22~.',waveform_data)
waveform_data
}
#good
prepare_vehicle <- function() {
vehicle_data <- read.table('~/Dropbox/School/CSE5393/sgd/vehicle.csv',sep=',',header=F,strip.white=T,
na.strings = '?')
vehicle_data$V19 <- factor(vehicle_data$V19)
vehicle_data <- discretizeDF.supervised('V19~.',vehicle_data)
vehicle_data
}
#good
prepare_zoo <- function() {
zoo_data <- read.table(url('http://archive.ics.uci.edu/ml/machine-learning-databases/zoo/zoo.data'),
sep=',',header=FALSE,na.strings='?')
zoo_data[,'V1'] <- NULL
zoo_data[,'V2'] <- factor(zoo_data[,'V2'])
zoo_data[,'V3'] <- factor(zoo_data[,'V3'])
zoo_data[,'V4'] <- factor(zoo_data[,'V4'])
zoo_data[,'V5'] <- factor(zoo_data[,'V5'])
zoo_data[,'V6'] <- factor(zoo_data[,'V6'])
zoo_data[,'V7'] <- factor(zoo_data[,'V7'])
zoo_data[,'V8'] <- factor(zoo_data[,'V8'])
zoo_data[,'V9'] <- factor(zoo_data[,'V9'])
zoo_data[,'V10'] <- factor(zoo_data[,'V10'])
zoo_data[,'V11'] <- factor(zoo_data[,'V11'])
zoo_data[,'V12'] <- factor(zoo_data[,'V12'])
zoo_data[,'V13'] <- factor(zoo_data[,'V13'])
zoo_data[,'V14'] <- factor(zoo_data[,'V14'])
zoo_data[,'V15'] <- factor(zoo_data[,'V15'])
zoo_data[,'V16'] <- factor(zoo_data[,'V16'])
zoo_data[,'V17'] <- factor(zoo_data[,'V17'])
zoo_data[,'V18'] <- factor(zoo_data[,'V18']) #Class variable
zoo_data
}
generate_folds <- function(data) {
data_indices <- 1:dim(data)[1]
shuffled_indices <- sample(data_indices)
split_indices <- split(shuffled_indices,rep(1:10,length(shuffled_indices)/10))
return(split_indices)
}
process_data <- function(data, data_label, test_fold, class_column, sup, conf,maxlength=10) {
#num_train_elems <- floor(dim(data)[1]*train_pct)
#train_idx <- sample(seq_len(nrow(data)), size=num_train_elems)
train_itemset <- data[-unlist(test_fold),]
train_data <- as(train_itemset,'transactions')
test_itemset <- data[unlist(test_fold),]
test_data <- as(test_itemset,'transactions')
data_rules <- apriori(train_data, parameter=list(support=sup, confidence = conf, maxlen=maxlength),
appearance = list(rhs=grep(class_column, itemLabels(train_data), value = TRUE), default = "lhs"),
control=list(verbose=F))
train_test <- list()
train_test[c('train','test','train_itemset','test_itemset','ruleset','class_column','label')] <- list(
train_data,test_data,train_itemset,test_itemset,data_rules,class_column,data_label)
train_test
}
mine_rules_nested <- function(data, data_indices, class_column, sup, conf,maxlength=10) {
train_data <- as(data[data_indices,],'transactions')
data_rules <- apriori(train_data, parameter=list(support=sup, confidence = conf, maxlen=maxlength),
appearance = list(rhs=grep(class_column, itemLabels(train_data), value = TRUE), default = "lhs"),
control=list(verbose=F))
data_rules
}
find_rules_per_class <- function(rules,method=2) {
if(method==1) {
classes <- unique(rhs(rules))
class_list <- list()
for(i in 1:length(classes)) {
class_list[length(class_list)+1] <- list(which(is.subset(rhs(rules),classes[i])))
}
class_list
} else {
rule_factor <- factor(unlist(as(rhs(rules),'list')))
num_classes <- length(levels(rule_factor))
rule_predictions <- as.integer(rule_factor)
class_rules <- matrix(nrow=length(rules),ncol=num_classes)
class_rules[,] <- 0
for(i in 1:num_classes) {
rule_indices <- which(rule_predictions==i)
class_rules[rule_indices,i] <- 1
}
class_rules
}
}
find_rules_per_transaction <- function(rules,transactions) {
t(is.subset(lhs(rules),transactions))
}
generate_labels <- function(itemset,class_column) {
class_names <- itemset[[class_column]]
class_numbers <- as.numeric(class_names)
class_ohe <- matrix(nrow=dim(itemset)[1],ncol=max(class_numbers))
class_ohe[,] <- 0
for(i in 1:dim(itemset)[1]) {
class_ohe[i,class_numbers[i]] <- 1
}
class_ohe
}
gen_starting_weights <- function(weight_mask) {
return(weight_mask)
}
get_batches <- function(total_size,batch_size) {
total_indices <- 1:total_size
shuffled_indices <- sample(total_indices)
split_indices <- split(shuffled_indices,rep(1:(length(shuffled_indices)/batch_size),length(shuffled_indices)/batch_size))
return(split_indices)
}
get_batch <- function(sparse_matrix, batch_indices=NULL) {
#print(paste('sparse matrix size',object.size(sparse_matrix),class(sparse_matrix)))
if(is.null(batch_indices)) {
res <- as.matrix(1*sparse_matrix)
#print(object.size(res))
return(res)
}
sparse_result <- sparse_matrix[batch_indices,]
res <- as.matrix(1*sparse_result)
#print(paste('batch size for',length(batch_indices),'items:',object.size(res)))
return(res)
}
#PRECONDITION: every transaction has at least 1 rule, b/c there is a default rule that guesses the majority class
#params list: (epoch,eta,batch_size,loss=['mse','cross'],optimizer=['sgd','adam','adadelta'],
# adam_params=[l_r,b1,b2,eps],adadelta_params=[l_r,rho,eps],
# regularization=[l1,l2],regularization_weights=[l1,l2])
build_and_run <- function(t_in,y_in,t_in_test,y_in_test,c_in,params,verbosity=0,logging=0) {
best_epoch <- 1
train_accs <- c()
test_accs <- c()
train_loss <- c()
test_loss <- c()
tf$reset_default_graph()
with(tf$Session() %as% sess,{
w_in <- gen_starting_weights(c_in)
num_rules <- dim(c_in)[1]
num_classes <- dim(c_in)[2]
C_ <- tf$placeholder(tf$float32, shape(num_rules,num_classes),name='C-tensor')
y_ <- tf$placeholder(tf$float32, shape(NULL, num_classes),name='y-tensor')
T_ <- tf$placeholder(tf$float32, shape(NULL,num_rules),name='T-tensor')
W <- tf$Variable(tf$ones(shape(num_rules,num_classes)),name='W-tensor')
if('patience' %in% names(params)) {
saver <<- tf$train$Saver(max_to_keep=params$patience+2L)
} else {
saver <<- tf$train$Saver()
}
W <- tf$multiply(W,C_)
W <- tf$nn$relu(W)
yhat <- tf$matmul(T_,W,a_is_sparse = T, b_is_sparse = T,name='yhat-tensor')
if(params$loss=='mse') {
loss <- tf$losses$mean_squared_error(y_,yhat)
} else if(params$loss=='cross') {
loss <- tf$losses$softmax_cross_entropy(y_,yhat)
}
if(params$regularization=='l1') {
regularizer <- tf$scalar_mul(params$regularization_weights$l1,tf$reduce_sum(tf$abs(W)))
loss <- tf$add(loss,regularizer)
} else if(params$regularization=='l2') {
regularizer <- tf$scalar_mul(params$regularization_weights$l1,tf$reduce_sum(tf$square(W)))
loss <- tf$reduce_mean(tf$add(loss,regularizer))
} else if(params$regularization=='elastic') {
l1 <- tf$scalar_mul(params$regularization_weights$l1,tf$reduce_sum(tf$abs(W)))
l2 <- tf$scalar_mul(params$regularization_weights$l1,tf$reduce_sum(tf$square(W)))
loss <- tf$reduce_mean(tf$add(tf$add(loss,l1),l2))
}
if(params$optimizer=='sgd') {
optimizer <- tf$train$GradientDescentOptimizer(params$learning_rate)
} else if(params$optimizer=='adam') {
optimizer <- tf$train$AdamOptimizer(params$adam_params$learning_rate,params$adam_params$beta1,
params$adam_params$beta2,params$adam_params$epsilon)
} else if(params$optimizer=='adadelta') {
optimizer <- tf$train$AdadeltaOptimizer(params$adadelta_params$learning_rate,params$adadelta_params$rho,
params$adadelta_params$epsilon)
} else {
stop('Error - please specify a valid optimizer!')
}
#print(paste(C_,y_,T_,W,loss,optimizer))
train_step <- optimizer$minimize(loss)
sess$run(tf$global_variables_initializer())
for(i in 1:params$epoch) {
batches <- get_batches(dim(t_in)[1],params$batch_size)
for(batch in batches) {
current_batch <- get_batch(t_in,batch)
#print(tail(sort( sapply(ls(),function(x){object.size(get(x))})) ))
sess$run(train_step,
feed_dict = dict(C_=c_in,T_=current_batch,y_=get_batch(y_in,batch)))
rm(current_batch)
}
if('early_stop' %in% names(params) | logging==1) {
train_accs <- c(train_accs,eval_accuracy(c_in,t_in,y_in,sess,T,params$batch_size))
train_loss <- c(train_loss,eval_loss(loss,c_in,t_in,y_in,sess,T,params$batch_size))
test_accs <- c(test_accs,eval_accuracy(c_in,t_in_test,y_in_test,sess,F))
test_loss <- c(test_loss,eval_loss(loss,c_in,t_in_test,y_in_test,sess,F))
saver$save(sess,paste0('/tmp/model-',i,'.ckpt'))
}
if('early_stop' %in% names(params)) {
if(params$early_stop == 'train_acc') {
eps <- 0.0001
if(train_accs[i]+eps > train_accs[best_epoch]) {
best_epoch <- i
} else if(i>best_epoch+params$patience) {
saver$restore(sess,paste0('/tmp/model-',best_epoch,'.ckpt'))
print(paste('Restored model to epoch',best_epoch))
break
}
} else if(params$early_stop == 'test_acc') {
eps <- 0.0001
if(test_accs[i]+eps > test_accs[best_epoch]) {
best_epoch <- i
} else if(i>best_epoch+params$patience) {
saver$restore(sess,paste0('/tmp/model-',best_epoch,'.ckpt'))
print(paste('Restored model to epoch',best_epoch))
break
}
}
}
if(verbosity>1) {
print(paste(i,'train acc:',eval_accuracy(c_in,t_in,y_in,sess,T,params$batch_size),'train loss:',eval_loss(loss,c_in,t_in,y_in,sess,T,params$batch_size)))
print(paste(' test acc:',eval_accuracy(c_in,t_in_test,y_in_test,sess,F),
'test loss:',eval_loss(loss,c_in,t_in_test,y_in_test,sess,F)))
num_rules <- sess$run(tf$count_nonzero(tf$nn$relu(W)),feed_dict=dict(C_=c_in)) #ADD RELU
print(paste(' num rules:',num_rules))
}
}
train_acc <- eval_accuracy(c_in,t_in,y_in,sess,T,params$batch_size)
test_acc <- eval_accuracy(c_in,t_in_test,y_in_test,sess,F)
num_rules <- sess$run(tf$count_nonzero(tf$nn$relu(W)),feed_dict=dict(C_=c_in)) #ADD RELU
if(verbosity>0) {
print(paste('Train acc:',train_acc,'Test acc:',test_acc))
#print(sess$run(W,
# feed_dict = dict(C_=c_in,T_=t_in[batch,],y_=y_in[batch,])))
}
if(logging==1) {
png('train_accs.png')
plot(train_accs)
dev.off()
png('test_accs.png')
plot(test_accs)
dev.off()
png('train_loss.png')
plot(train_loss)
dev.off()
png('test_loss.png')
plot(test_loss)
dev.off()
}
#print(tail(sort(sapply(ls(),function(x){object.size(get(x))})) ))
return(c(train_acc,test_acc,num_rules))
})
}
CWAR <- function(class_rules,train_trans_rules,train_trans_labels,validation_trans_rules,validation_trans_labels,
params,verbosity=0,logging=0) {
best_epoch <- 1
tf$reset_default_graph()
with(tf$Session() %as% sess,{
num_rules <- dim(class_rules)[1]
num_classes <- dim(class_rules)[2]
C_ <- tf$placeholder(tf$float32, shape(num_rules,num_classes),name='C-tensor')
y_ <- tf$placeholder(tf$float32, shape(NULL, num_classes),name='y-tensor')
T_ <- tf$placeholder(tf$float32, shape(NULL,num_rules),name='T-tensor')
W <- tf$Variable(tf$ones(shape(num_rules,num_classes)),name='W-tensor')
if('patience' %in% names(params)) {
saver <<- tf$train$Saver(max_to_keep=params$patience+2L)
} else {
saver <<- tf$train$Saver()
}
W <- tf$multiply(W,C_)
W <- tf$nn$relu(W)
yhat <- tf$matmul(T_,W,a_is_sparse = T, b_is_sparse = T,name='yhat-tensor')
if(params$loss=='mse') {
loss <- tf$losses$mean_squared_error(y_,yhat)
} else if(params$loss=='cross') {
loss <- tf$losses$softmax_cross_entropy(y_,yhat)
}
if(params$regularization=='l1') {
regularizer <- tf$scalar_mul(params$regularization_weights$l1,tf$reduce_sum(tf$abs(W)))
loss <- tf$add(loss,regularizer)
} else if(params$regularization=='l2') {
regularizer <- tf$scalar_mul(params$regularization_weights$l1,tf$reduce_sum(tf$square(W)))
loss <- tf$reduce_mean(tf$add(loss,regularizer))
} else if(params$regularization=='elastic') {
l1 <- tf$scalar_mul(params$regularization_weights$l1,tf$reduce_sum(tf$abs(W)))
l2 <- tf$scalar_mul(params$regularization_weights$l1,tf$reduce_sum(tf$square(W)))
loss <- tf$reduce_mean(tf$add(tf$add(loss,l1),l2))
}
if(params$optimizer=='sgd') {
optimizer <- tf$train$GradientDescentOptimizer(params$learning_rate)
} else if(params$optimizer=='adam') {
optimizer <- tf$train$AdamOptimizer(params$adam_params$learning_rate,params$adam_params$beta1,
params$adam_params$beta2,params$adam_params$epsilon)
} else if(params$optimizer=='adadelta') {
optimizer <- tf$train$AdadeltaOptimizer(params$adadelta_params$learning_rate,params$adadelta_params$rho,
params$adadelta_params$epsilon)
} else {
stop('Error - please specify a valid optimizer!')
}
train_step <- optimizer$minimize(loss)#problem line
sess$run(tf$global_variables_initializer())
for(i in 1:params$epoch) {
batches <- get_batches(dim(train_trans_rules)[1],params$batch_size)
for(batch in batches) {
current_batch <- get_batch(train_trans_rules,batch)
sess$run(train_step,
feed_dict = dict(C_=class_rules,T_=current_batch,y_=get_batch(train_trans_labels,batch)))
rm(current_batch)
}
}
model <- list(model=NULL,class_rules=class_rules,validation_accuracy=0,num_rules=0)
val_acc <- evaluate_model_accuracy(model,validation_trans_rules,validation_trans_labels,batch_size=params$batch_size)
n_rules <- sess$run(tf$count_nonzero(tf$nn$relu(W)),feed_dict=dict(C_=class_rules)) #ADD RELU
model$validation_accuracy <- val_acc
model$num_rules <- n_rules
model$weights <- sess$run(W,feed_dict=dict(C_=class_rules)) #combine this with n_rules above
return(model)
})
}
run_grid_search <- function(class_rules,train_trans_rules,train_trans_labels,validation_trans_rules,validation_trans_labels,
parameters,verbosity,logging,history=F,tested_models=list()) {
best_model <<- list(validation_accuracy=0)
param_index <<- 1
for(loss_function in parameters$loss) {
for(opt in parameters$optimizer) {
for(reg in parameters$regularization) {
for(reg_weights in parameters$regularization_weights) {
for(l_rate in parameters$learning_rate) {
for(epoch in parameters$epochs) {
current_params <- list(loss=loss_function,optimizer=opt,regularization=reg,regularization_weights=reg_weights,
learning_rate=l_rate,epochs=epoch,batch_size=parameters$batch_size,
adam_params=parameters$adam_params)
current_model <- CWAR(class_rules,train_trans_rules,train_trans_labels,validation_trans_rules,validation_trans_labels,
current_params,verbosity,logging)
if(current_model$validation_accuracy > best_model$validation_accuracy) {
best_model <- current_model
}
if(length(tested_models) < param_index) {
tested_models[[param_index]] <- list(val_acc=c(current_model$validation_accuracy),
rule_size=c(current_model$num_rules))
} else {
tested_models[[param_index]]$val_acc <- c(tested_models[[param_index]]$val_acc,current_model$validation_accuracy)
tested_models[[param_index]]$rule_size <- c(tested_models[[param_index]]$rule_size,current_model$num_rules)
}
param_index <- param_index + 1
}
}
}
}
}
}
#print(paste('gridsearched',param_index,'params'))
if(history) {
#FLAG
return(list(best=best_model,history=tested_models))
} else {
return(list(best=best_model))
}
}
#THIS IS THE BOTTLENECK - IT REQUIRES THE WHOLE T NOT JUST THE BATCHES
eval_accuracy <- function(c_in,t_in,y_in,sess,batching=T,batch_size=0) {
graph <- tf$get_default_graph()
y_ <- graph$get_tensor_by_name('y-tensor:0')
yhat <- graph$get_tensor_by_name('yhat-tensor:0')
correct_prediction <- tf$equal(tf$argmax(yhat,1L),tf$argmax(y_,1L))
accuracy <- tf$reduce_mean(tf$cast(correct_prediction,tf$float32))
acc <<- 0
if(batching) {
batches <- get_batches(dim(t_in)[1],batch_size)
for(batch in batches) {
acc <- acc + accuracy$eval(feed_dict=dict('C-tensor:0'=c_in,'T-tensor:0'=get_batch(t_in,batch),'y-tensor:0'=get_batch(y_in,batch)),session=sess)
}
} else {
return(accuracy$eval(feed_dict=dict('C-tensor:0'=c_in,'T-tensor:0'=get_batch(t_in),'y-tensor:0'=y_in),session=sess))
}
return(acc/length(batches))
}
eval_loss <- function(loss,c_in,t_in,y_in,sess,batching=T,batch_size=0) {
if(batching) {
batches <- get_batches(dim(t_in)[1],batch_size)
lss <<- 0
for(batch in batches) {
lss <- lss + loss$eval(feed_dict=dict('C-tensor:0'=c_in,'T-tensor:0'=get_batch(t_in,batch),'y-tensor:0'=get_batch(y_in,batch)),session=sess)
}
} else {
return(loss$eval(feed_dict=dict('C-tensor:0'=c_in,'T-tensor:0'=get_batch(t_in),'y-tensor:0'=y_in),session=sess))
}
return(lss/length(batches))
}
get_baseline_accuracy <- function(trans_rules,trans_rules_test,y_in,y_in_test,w_in,verbosity=0) {
train_guesses <- apply(trans_rules%*%w_in,1,function(x) which.max(x))
train_labels <- apply(y_in,1,function(x) which.max(x))
train_acc <- sum(train_guesses==train_labels)/length(train_guesses)
test_guesses <- apply(trans_rules_test%*%w_in,1,function(x) which.max(x))
test_labels <- apply(y_in_test,1,function(x) which.max(x))
test_acc <- sum(test_guesses==test_labels)/length(test_guesses)
if(verbosity>0) {
print(paste('Baseline train acc:',train_acc,'Baseline test acc:',test_acc))
}
return(c(train_acc,test_acc,dim(w_in)[1]))
}
evaluate_model_accuracy <- function(model,trans_rules,trans_labels,batching=T,batch_size=16) {
graph <- tf$get_default_graph()
sess <- tf$get_default_session()
y_ <- graph$get_tensor_by_name('y-tensor:0')
yhat <- graph$get_tensor_by_name('yhat-tensor:0')
correct_prediction <- tf$equal(tf$argmax(yhat,1L),tf$argmax(y_,1L))
accuracy <- tf$reduce_mean(tf$cast(correct_prediction,tf$float32))
acc <<- 0
if(batching) {
batches <- get_batches(dim(trans_rules)[1],batch_size)
for(batch in batches) {
acc <- acc + accuracy$eval(feed_dict=dict('C-tensor:0'=model$class_rules,
'T-tensor:0'=get_batch(trans_rules,batch),
'y-tensor:0'=get_batch(trans_labels,batch)),session=sess)
}
return(acc/length(batches))
} else {
return(accuracy$eval(feed_dict=dict('T-tensor:0'=get_batch(trans_rules),'y-tensor:0'=get_batch(trans_labels),session=sess)))
}
}
evaluate_baseline_accuracy <- function(trans_rules,trans_labels,class_rules,verbosity) {
guesses <- apply(trans_rules%*%class_rules,1,function(x) which.max(x))
labels <- apply(trans_labels,1,function(x) which.max(x))
acc <- sum(guesses==labels)/length(guesses)
if(verbosity>0) {
print(paste('Baseline train acc:',train_acc,'Baseline test acc:',test_acc))
}
return(acc)
}
evaluate_rf_accuracy <- function(train_data,test_data,class_column,time=F) {
target <- formula(paste0(class_column,'~.'))
clf <- randomForest(target,data=train_data)
pred <- predict(clf,test_data)
acc <- sum(pred==test_data[[class_column]])/length(pred)
if(time) {
start_time <- proc.time()[1]
for(j in 1:500) {
predict(clf,test_data)
}
print(paste('rf time',proc.time()[1]-start_time))
}
return(acc)
}
get_cba_accuracy <- function(dataset,support,confidence,maxlength=10) {
if(maxlength<10) {
return(c(0,0,0))
}
data_target <- paste(dataset$class_column,'~.',sep='')
cba <- CBA(data_target, data=dataset$train_itemset, parameter=list(maxlen=maxlength),
support=support,confidence=confidence)
num_rules <- length(cba$rules)
train_prediction <- predict(cba,dataset$train_itemset)
test_prediction <- predict(cba,dataset$test_itemset)
train_acc <- sum(train_prediction==dataset$train_itemset[[dataset$class_column]])/length(dataset$train_itemset[[dataset$class_column]])
test_acc <- sum(test_prediction==dataset$test_itemset[[dataset$class_column]])/length(dataset$test_itemset[[dataset$class_column]])
return(c(train_acc,test_acc,num_rules))
}
run_cross_validation <- function(name,raw_data,class_column,support,confidence,parameters,verbosity,logging,maxlength=10) {
print(paste('Running cross validation for',name,'data with',dim(raw_data)[1],'transactions total'))
folds <- generate_folds(raw_data)
cba_train <- c()
cba_train_rules <- c()
cba_test <- c()
baseline_train <- c()
baseline_train_rules <- c()
baseline_test <- c()
acc_train <- c()
train_rules <- c()
acc_test <- c()
for(i in 1:10) {
if(i>1) {
#return(T)
next
}
if(verbosity>-1) {
print(paste('Running',name,'data on fold',i,'with',length(unlist(folds[i])),'test transactions'))
}
data <- process_data(raw_data,name,folds[i],class_column,support,confidence,maxlength=maxlength)
#print(paste('Finished process data method in',as.numeric(t[2])))
if(verbosity>-1) {
print(paste('Mined',length(data$ruleset),'rules'))
}
class_rules <- find_rules_per_class(data$ruleset)
trans_rules <- find_rules_per_transaction(data$ruleset,data$train) #THIS IS THE BOTTLENECK
trans_rules_test <- find_rules_per_transaction(data$ruleset,data$test)#THIS IS A LIE!!!
trans_labels <- generate_labels(data$train_itemset,data$class_column)
trans_labels_test <- generate_labels(data$test_itemset,data$class_column)
baseline_accs <- get_baseline_accuracy(trans_rules,trans_rules_test,trans_labels,
trans_labels_test,class_rules,verbosity=verbosity)
cba_results <- get_cba_accuracy(data,support,confidence,maxlength=maxlength)
baseline_train <- c(baseline_train,baseline_accs[1])
baseline_test <- c(baseline_test,baseline_accs[2])
baseline_train_rules <- c(baseline_train_rules,baseline_accs[3])
cba_train <- c(cba_train,cba_results[1])
cba_test <- c(cba_test,cba_results[2])
cba_train_rules <- c(cba_train_rules,cba_results[3])
accs <- build_and_run(t_in=trans_rules,y_in=trans_labels,t_in_test=trans_rules_test,
y_in_test=trans_labels_test,c_in=class_rules,params=parameters,verbosity=verbosity,logging=logging)
acc_train <- c(acc_train,accs[1])
acc_test <- c(acc_test,accs[2])
train_rules <- c(train_rules,accs[3])
}
print(paste('Average baseline accs - train:',mean(baseline_train),'test:',mean(baseline_test)))
print(paste(' baseline rules:',mean(baseline_train_rules)))
print(paste('Average cba accs - train:',mean(unlist(cba_train)),'test:',mean(unlist(cba_test))))
print(paste(' cba rules:',mean(unlist(cba_train_rules))))
print(paste('Average accs - train:',mean(acc_train),'test:',mean(acc_test)))
print(paste(' rules:',mean(train_rules)))
}
make_classifier <- function(rules,weights,formula) {
rule_weights <- rowSums(weights)
rules_to_keep <- which(rule_weights!=0)
new_rules <- rules[rules_to_keep]
new_rule_weights <- rule_weights[rules_to_keep]
classifier <- CBA_ruleset(formula=formula,
rules=new_rules,
weights = new_rule_weights,
method = 'majority'
)
return(classifier)
}
run_nested_cross_validation <- function(name,raw_data,class_column,support,confidence,parameters,verbosity,logging,maxlength=10,
compare_rf=T,compare_time=F) {
num_transactions <- dim(raw_data)[1]
print(paste('Running cross validation for',name,'data with',num_transactions,'transactions total'))
folds <- generate_folds(raw_data)
test_accuracy_list <- c()
ruleset_size_list <- c()
models <- list()
baseline_test_accuracy_list <- c()
rf_test_accuracy_list <- c()
for(i in 1:length(folds)) {
if(i>3) {
#return(T)
next
}
test_indices <- unlist(folds[i])
train_indices <- setdiff(1:num_transactions,test_indices)
validation_indices <- sample(train_indices,length(train_indices)/5)
train_indices <- setdiff(train_indices,validation_indices)
if(verbosity>-1) {
print(paste('Running',name,'data on fold',i,'with',length(train_indices),'train transactions',
length(validation_indices),'val transactions, and',length(test_indices),'test transactions'))
}
rules <- mine_rules_nested(raw_data,train_indices,class_column,support,confidence,maxlength=maxlength)
if(verbosity>-1) {
print(paste('Mined',length(rules),'rules'))
}
class_rules <- find_rules_per_class(rules)
#rm(rules)
train_trans_rules <- find_rules_per_transaction(rules,as(raw_data[train_indices,],'transactions')) #THIS IS THE BOTTLENECK
train_trans_labels <- generate_labels(raw_data[train_indices,],class_column)
validation_trans_rules <- find_rules_per_transaction(rules,as(raw_data[validation_indices,],'transactions'))
validation_trans_labels <- generate_labels(raw_data[validation_indices,],class_column)
grid_search_results <- run_grid_search(class_rules,train_trans_rules,train_trans_labels,validation_trans_rules,validation_trans_labels,
parameters,verbosity,logging,history=T,tested_models=models)
#parameters,verbosity,logging,history=F)
best_model <- grid_search_results$best
models <- grid_search_results$history
if(verbosity>0 & i==10) {
print(models)
}
rm(train_trans_rules,train_trans_labels,validation_trans_rules,validation_trans_labels)
test_trans_rules <- find_rules_per_transaction(rules,as(raw_data[test_indices,],'transactions'))
test_trans_labels <- generate_labels(raw_data[test_indices,],class_column)
#FLAG
#model_test_acc <- evaluate_model_accuracy(best_model,test_trans_rules,test_trans_labels,batch_size=parameters$batch_size)
model_test_acc <- evaluate_baseline_accuracy(test_trans_rules,test_trans_labels,best_model$weights,verbosity)
test_accuracy_list <- c(test_accuracy_list,model_test_acc)
ruleset_size_list <- c(ruleset_size_list,best_model$num_rules)
baseline_test_acc <- evaluate_baseline_accuracy(test_trans_rules,test_trans_labels,class_rules,verbosity=verbosity)
baseline_test_accuracy_list <- c(baseline_test_accuracy_list,baseline_test_acc)
if(compare_rf) {
rf_test_acc <- evaluate_rf_accuracy(raw_data[train_indices,],raw_data[test_indices,],class_column)
rf_test_accuracy_list <- c(rf_test_accuracy_list,rf_test_acc)
}
if(i==10 & compare_time) {
target <- formula(paste0(class_column,'~.'))
classifier <- make_classifier(rules,best_model$weights,target)
test_data <- raw_data[test_indices,]
start_time <- proc.time()[1]
for(j in 1:500) {
predict(classifier,test_data)
}
print(paste('classifier time',proc.time()[1]-start_time))
evaluate_rf_accuracy(raw_data[train_indices,],raw_data[test_indices,],class_column,T)
}
#cba_test_acc <- evaluate_cba_accuracy()
}
print(paste('Average model test accuracy:',mean(test_accuracy_list)))
print(paste('Average model ruleset size:',mean(ruleset_size_list)))
print(paste('Average baseline test accuracy:',mean(baseline_test_accuracy_list)))
print(paste('Average rf test accuracy:',mean(rf_test_accuracy_list)))
}
adam_p <- list(learning_rate=0.1,beta1=0.9,beta2=0.999,epsilon=1e-08)
adadelta_p <- list(learning_rate=0.001,rho=0.95,epsilon=1e-08)
#reg_weights <- list(l1=0.1,l2=0.01)
reg_weights_2 <- list(l1=0.01,l2=0.01)
reg_weights_3 <- list(l1=0.001,l2=0.01)
reg_weights_4 <- list(l1=0.0001,l2=0.01)
reg_weights_5 <- list(l1=0.0001,l2=0.05)
reg_weights_6 <- list(l1=0.001,l2=0.0001)
gridsearch_p <- list(epochs=c(5,10),learning_rate=c(0.05,0.2,0.5),batch_size=16,loss=c('cross'),optimizer=c('adam'),adam_params=adam_p,
regularization=c('l1'),regularization_weights=list(reg_weights_2,reg_weights_3,reg_weights_4,
reg_weights_5,reg_weights_6))#,early_stop='test_acc',patience=4L)
run_nested_cross_validation('Breast',prepare_bc(),'V11',0.01,0.5,gridsearch_p,verbosity=0,logging=0,compare_rf = T,compare_time=T)
run_nested_cross_validation('Cleve',prepare_cleve(),'V14',0.01,0.5,gridsearch_p,verbosity=0,logging=1,compare_rf=T,compare_time=T)
run_nested_cross_validation('Glass',prepare_glass(),'V11',0.01,0.5,gridsearch_p,verbosity=0,logging=0,compare_rf=T,compare_time=T)
run_nested_cross_validation('Heart',prepare_heart(),'V14',0.01,0.5,gridsearch_p,verbosity=0,logging=0,compare_rf=T,compare_time=T)
run_nested_cross_validation('Iris',prepare_iris(),'V4',0.01,0.5,gridsearch_p,verbosity=0,logging=0,compare_rf=T,compare_time=T)
#run_nested_cross_validation("Labor",prepare_labor(),'V17',0.01,0.5,gridsearch_p,verbosity=0,logging=0)
run_nested_cross_validation("LED7",prepare_led7(),'V8',0.01,0.5,gridsearch_p,verbosity=0,logging=0,compare_rf=T,compare_time=T)
run_nested_cross_validation("Pima",prepare_pima(),'V9',0.01,0.5,gridsearch_p,verbosity=0,logging=0,compare_rf=T,compare_time=T)
run_nested_cross_validation("Tic",prepare_tic(),'V10',0.01,0.5,gridsearch_p,verbosity=0,logging=0,compare_rf=T,compare_time=T)
#run_nested_cross_validation("Wine",prepare_wine(),'V13',0.01,0.5,gridsearch_p,verbosity=0,logging=0)
#p <- list(epochs=40,learning_rate=0.05,batch_size=16,loss='cross',optimizer='sgd',adam_params=adam_p)
p <- list(epochs=2,learning_rate=0.55,batch_size=16,loss='cross',optimizer='adam',adam_params=adam_p,
regularization='l1',regularization_weights=reg_weights)#,early_stop='test_acc',patience=4L)
#NOTE: early stopping will increase accuracy at the cost of ruleset size. Also, it's probably fake unless I use a validation set
run_cross_validation('Anneal',prepare_anneal(),'V39',0.01,0.5,p,verbosity=0,logging=1,maxlen=6)
run_cross_validation('Austral',prepare_austral(),'V15',0.01,0.5,p,verbosity=0,logging=1)
#run_cross_validation('Auto',prepare_auto(),'V26',0.04,0.5,p,verbosity=0,logging=1,maxlength=6)#Fails
run_cross_validation('Breast',prepare_bc(),'V11',0.01,0.5,p,verbosity=0,logging=1)
run_cross_validation('CRX',prepare_crx(),'V16',0.01,0.5,p,verbosity=0,logging=0,maxlen=9)
run_cross_validation('Cleve',prepare_cleve(),'V14',0.02,0.5,p,verbosity=0,logging=1)
run_cross_validation('German',prepare_german(),'V21',0.024,0.5,p,verbosity=0,logging=0,maxlen=9)
run_cross_validation('Glass',prepare_glass(),'V11',0.01,0.5,p,verbosity=0,logging=1)
run_cross_validation('Heart',prepare_heart(),'V14',0.01,0.5,p,verbosity=0,logging=1)
run_cross_validation('Hepatic',prepare_hepatic(),'V20',0.03,0.5,p,verbosity=0,logging=0,maxlen=9)#TOO BIG
run_cross_validation('Horse',prepare_horse(),'V40',0.01,0.5,p,verbosity=0,logging=1,maxlen=9)
run_cross_validation("Iono",prepare_iono(),'V35',0.05,0.5,p,verbosity=0,logging=1,maxlen=6)
run_cross_validation("Iris",prepare_iris(),'V5',0.01,0.5,p,verbosity=0,logging=1)
run_cross_validation("Labor",prepare_labor(),'V17',0.03,0.5,p,verbosity=0,logging=1)
run_cross_validation("LED7",prepare_led7(),'V8',0.01,0.5,p,verbosity=0,logging=1)
run_cross_validation("Lymph",prepare_lymph(),'V19',0.04,0.5,p,verbosity=0,logging=1)
run_cross_validation("Pima",prepare_pima(),'V9',0.01,0.5,p,verbosity=0,logging=1)
run_cross_validation("Sick",prepare_sick(),'V30',0.23,0.5,p,verbosity=0,logging=1,maxlen=7)
run_cross_validation("Sonar",prepare_sonar(),'V61',0.04,0.5,p,verbosity=0,logging=1)
run_cross_validation("Tic",prepare_tic(),'V10',0.01,0.5,p,verbosity=0,logging=1)
run_cross_validation("Wine",prepare_wine(),'V13',0.01,0.5,p,verbosity=0,logging=0)
run_cross_validation("Waveform",prepare_waveform(),'V22',0.025,0.5,p,verbosity=0,logging=0,maxlen=9)
run_cross_validation("Vehicle",prepare_vehicle(),'V19',0.05,0.5,p,verbosity=0,logging=0,maxlen=8)
#run_cross_validation("Zoo",prepare_zoo(),'V18',0.055,0.5,p,verbosity=0,logging=1,maxlen=10) #too class-imbalanced
} |
97b3b2f40f77696b459752a0bdf26b6aa61a4002 | b42b794892a9b3fd492d627acdc046c90df62af0 | /man/fars_read.Rd | 6f9348e455055ea3e66ebd6c9dca366bf814cb7b | [] | no_license | dddbbb/fars | 11aab51d53031c5e47494d0efc9c380b6e761fe1 | 95baaf2a3c27a91bb5990b5bfb15a7f1351e961e | refs/heads/master | 2020-05-26T13:29:52.319181 | 2017-02-19T19:44:47 | 2017-02-19T19:44:47 | 82,480,910 | 0 | 0 | null | null | null | null | UTF-8 | R | false | true | 503 | rd | fars_read.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/fars_functions.R
\name{fars_read}
\alias{fars_read}
\title{Read FARS data}
\usage{
fars_read(filename)
}
\arguments{
\item{filename}{Integer or string name of file for reading}
}
\value{
data.frame is output of the function
}
\description{
Reads data into data.frame from working directory.
.csv file should be already downloaded or error message will throw out
}
\examples{
\dontrun{
fars_read("accident_2015.csv.bz2")
}
}
|
d8939db003cafd23d66f57075d78ff151f19131e | 49859dc68647c5782fa4ce2bdeb703bd28cb81db | /man/gr.kmedoids.Rd | 7db9e00bc9aef79320c3d88ed99d3368c3826179 | [] | no_license | cran/RiemGrassmann | de43079eadef1dd0d82c3151752ffa7fc8b83eb4 | 36674fa8ecb807ed9733095383c470f96821bb43 | refs/heads/master | 2022-04-12T18:06:43.052688 | 2020-03-25T14:50:06 | 2020-03-25T14:50:06 | 250,133,406 | 0 | 0 | null | null | null | null | UTF-8 | R | false | true | 2,927 | rd | gr.kmedoids.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/gr_kmedoids.R
\name{gr.kmedoids}
\alias{gr.kmedoids}
\title{k-Medoids Clustering on Grassmann Manifold}
\usage{
gr.kmedoids(
input,
k = 2,
type = c("Intrinsic", "Extrinsic", "Asimov", "Binet-Cauchy", "Chordal",
"Fubini-Study", "Martin", "Procrustes", "Projection", "Spectral")
)
}
\arguments{
\item{input}{either an array of size \eqn{(n\times k\times N)} or a list of length \eqn{N} whose elements are \eqn{(n\times k)} orthonormal basis (ONB) on Grassmann manifold.}
\item{k}{the number of clusters}
\item{type}{type of distance measure. measure. Name of each type is \emph{Case Insensitive} and \emph{hyphen} can be omitted.}
}
\value{
an object of class \code{pam}. See \code{\link[cluster]{pam}} for details.
}
\description{
k-Medoids algorithm depends solely on the availability of concept that gives dissimilarity. We adopt \code{pam} algorithm
from \pkg{cluster} package. See \code{\link[cluster]{pam}} for more details.
}
\examples{
## generate a dataset with two types of Grassmann elements
# group1 : first four columns of (8x8) identity matrix + noise
# group2 : last four columns of (8x8) identity matrix + noise
mydata = list()
sdval = 0.25
diag8 = diag(8)
for (i in 1:10){
mydata[[i]] = qr.Q(qr(diag8[,1:4] + matrix(rnorm(8*4,sd=sdval),ncol=4)))
}
for (i in 11:20){
mydata[[i]] = qr.Q(qr(diag8[,5:8] + matrix(rnorm(8*4,sd=sdval),ncol=4)))
}
## do k-medoids clustering with 'intrinsic' distance
# First, apply MDS for visualization
dmat = gr.pdist(mydata, type="intrinsic")
embd = stats::cmdscale(dmat, k=2)
# Run 'gr.kmedoids' with different numbers of clusters
grint2 = gr.kmedoids(mydata, type="intrinsic", k=2)$clustering
grint3 = gr.kmedoids(mydata, type="intrinsic", k=3)$clustering
grint4 = gr.kmedoids(mydata, type="intrinsic", k=4)$clustering
# Let's visualize
opar <- par(no.readonly=TRUE)
par(mfrow=c(1,3), pty="s")
plot(embd, pch=19, col=grint2, main="k=2")
plot(embd, pch=19, col=grint3, main="k=3")
plot(embd, pch=19, col=grint4, main="k=4")
par(opar)
\donttest{
## perform k-medoids clustering with different distance measures
# iterate over all distance measures
alltypes = c("intrinsic","extrinsic","asimov","binet-cauchy",
"chordal","fubini-study","martin","procrustes","projection","spectral")
ntypes = length(alltypes)
labels = list()
for (i in 1:ntypes){
labels[[i]] = gr.kmedoids(mydata, k=2, type=alltypes[i])$clustering
}
## visualize
# 1. find MDS scaling for each distance measure as well
embeds = list()
for (i in 1:ntypes){
pdmat = gr.pdist(mydata, type=alltypes[i])
embeds[[i]] = stats::cmdscale(pdmat, k=2)
}
# 2. plot the clustering results
opar <- par(no.readonly=TRUE)
par(mfrow=c(2,5), pty="s")
for (i in 1:ntypes){
pm = paste0("k-medoids::",alltypes[i])
plot(embeds[[i]], col=labels[[i]], main=pm, pch=19)
}
par(opar)
}
}
\author{
Kisung You
}
|
12ace7ed90603617344d66f7c7ac02092b8cce70 | 4ed6dfdbac828314df254c82b9dab547d7167a79 | /04.ExploratoryDataAnalysis/video_lectures/week2.video06.ggplot2Part4.v1.R | 65df44b3fd0e9abc5c1f8da6844eaf6d12beb134 | [] | no_license | minw2828/datasciencecoursera | beb40d1c29fc81755a7b1f37fc5559d450b5a9e0 | e1b1d5d0c660bc434b1968f65c52987fa1394ddb | refs/heads/master | 2021-03-22T00:15:15.147227 | 2015-08-21T07:55:10 | 2015-08-21T07:55:10 | 35,082,087 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 292 | r | week2.video06.ggplot2Part4.v1.R | ## ggplot2 (part 4)
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
|
dd62add6bebfd4727db51fd1e4f0290458bbffbc | 32e401807cfee3c00e52c82e1998200f7b0ac227 | /Scripts/Analysis.R | 06fe968c7b8258b8972af7e208d80c261f31a74f | [] | no_license | crushing05/stopover_assign | e94bbf4476637bc985fba0d9cd4ec4418d72a9a8 | bbf16ba8ef461063e40e12f0e8a8b974e9a11cac | refs/heads/master | 2021-01-10T12:42:00.062667 | 2017-11-30T17:06:56 | 2017-11-30T17:06:56 | 53,863,151 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 86,042 | r | Analysis.R | install.packages("devtools")
devtools::install_github("crushing05/iso.assign2", force = TRUE)
#devtools::install_github("crushing05/crushingr")
require(devtools)
require(Rcpp)
require(tibble)
require(DBI)
#require(crushingr)
require(iso.assign2)
require(tidyr)
require(ggplot2)
require(dplyr)
#require(purrr)
#bring in data
#Run Data_prep code first to make the dat file
dat <- read.csv("Processed data/stop_iso_data.csv") #stop_iso_data.csv
head(dat)
names(dat)
summary(dat$site)
summary(dat$age)
table(dat$site,dat$age)
summary(dat$sex)
table(dat$site,dat$sex)
summary(dat$fat)
summary(dat$wing)
summary(dat$mass)
summary(dat$day.yr)
#File has attributes: site,band.no,year,species,date,age,sex,fat,wing,mass,day.yr dd cc
## Read basemap data
amre_base <- read.csv("Processed data/amre_base.csv")
oven_base <- read.csv("Raw data/oven_base.csv")
woth_base <- read.csv("Raw data/woth_base.csv")
############################################################
# Questions:
# 1. Does destination vary among sites? Lat ~ site
# 2. Does passage day vary by breeding latitude? DOY ~ Lat + site
# 2. Does passage day, relative to destination, vary for age or sex among sites?
# 3. Does passage day, relative to destination, vary with dC13?
# 3. Does condition, relative to destination, vary with dC13?
# Explore differences between sites in species numbers, age, sex, passage timing.
# Maps and Plots
############################################################
# AMRE #
############################################################
### Assign birds using weighted abundance
############################################################
## Convert date from factor to date in dat file
#dat$date <- as.Date(dat$date, format = "%Y-%m-%d")
# ##AMRE ASSIGN: estimate the likelihood of origin and likely/unlikely origins for stable hydrogen isotope samples
# amre_dd <- dat %>% filter(species == "AMRE")
# ## Subset AMRE data by site
# amre_app_dd <- amre_dd %>% filter(site == "APP")
# amre_job_dd <- amre_dd %>% filter(site == "JOB")
# amre_mad_dd <- amre_dd %>% filter(site == "MAD")
# ## Assign individuals from each site
# amre_app_assign <- iso_assign(dd = amre_app_dd$dd, df_base = amre_base$df.ahy, lat = amre_base$y, lon = amre_base$x, names = amre_app_dd$band.no)
# amre_job_assign <- iso_assign(dd = amre_job_dd$dd, df_base = amre_base$df.ahy, lat = amre_base$y, lon = amre_base$x, names = amre_job_dd$band.no)
# amre_mad_assign <- iso_assign(dd = amre_mad_dd$dd, df_base = amre_base$df.ahy, lat = amre_base$y, lon = amre_base$x, names = amre_mad_dd$band.no)
# #add weighteing by abundnace
# amre_app_assign2 <- abun_assign(iso_data = amre_app_assign, rel_abun = amre_base$rel.abun, iso_weight = 0, abun_weight = -1)
# amre_job_assign2 <- abun_assign(iso_data = amre_job_assign, rel_abun = amre_base$rel.abun, iso_weight = 0, abun_weight = -1)
# amre_mad_assign2 <- abun_assign(iso_data = amre_mad_assign, rel_abun = amre_base$rel.abun, iso_weight = 0, abun_weight = -1)
# head(amre_app_assign)
# summary(amre_mad_assign$lat)
# ## Create dataframe with assignment results
# ##convert to a matrix to rearange
# amre_app_mat <- matrix(amre_app_assign2$wght_origin, nrow = nrow(amre_base), ncol = length(amre_app_dd$dd), byrow = FALSE)
# amre_job_mat <- matrix(amre_job_assign2$wght_origin, nrow = nrow(amre_base), ncol = length(amre_job_dd$dd), byrow = FALSE)
# amre_mad_mat <- matrix(amre_mad_assign2$wght_origin, nrow = nrow(amre_base), ncol = length(amre_mad_dd$dd), byrow = FALSE)
# amre_assign <- data.frame(Latitude = amre_base$y,
# Longitude = amre_base$x,
# app_origin = apply(amre_app_mat, 1, sum)/ncol(amre_app_mat),
# job_origin = apply(amre_job_mat, 1, sum)/ncol(amre_job_mat),
# mad_origin = apply(amre_mad_mat, 1, sum)/ncol(amre_mad_mat))
# ## Write results to ~Results
# write.csv(amre_assign, file = "Results/amre_assign.csv", row.names = FALSE)
#loop through individuals from a site, in columns
#app
# amre_app_coord <- iso.assign2::wght_coord(summ = amre_app_assign2, iso = FALSE) %>% rename(band.no = indv) %>%
# left_join(., amre_app_dd)
# #job
# amre_job_coord <- iso.assign2::wght_coord(summ = amre_job_assign2, iso = FALSE) %>% rename(band.no = indv) %>%
# left_join(., amre_job_dd)
# #mad
# amre_mad_coord <- iso.assign2::wght_coord(summ = amre_mad_assign2, iso = FALSE) %>% rename(band.no = indv) %>%
# left_join(., amre_mad_dd)
# names(amre_mad_coord)
############################################################
############################################################
# Questions:
# 1. Does destination vary among sites? Lat ~ site
############################################################
#Merge file with attributes and mean lat long for all AMRE -- need to do this first
# amre_dd.ll<-rbind(amre_app_coord,amre_job_coord)
# amre_dd.ll<-rbind(amre_dd.ll,amre_mad_coord)
nrow(amre_dd.ll) #97
#change order of levels for sites
amre_dd.ll$Fsite<- factor(amre_dd.ll$site, levels = c("MAD","JOB","APP"), labels=c("Texas","Louisiana","Florida"))
#summary(amre_dd.ll)
table(amre_dd.ll$site)
table(amre_dd.ll$Fsite)
table(amre_dd.ll$site, amre_dd.ll$age)
table(amre_dd.ll$site, amre_dd.ll$sex)
table(amre_dd.ll$sex)
summary(amre_dd.ll$year)
amre_dd.ll$Fyear<- factor(amre_dd.ll$year, levels = c("2012","2013","2014"))
table(amre_dd.ll$Fyear)
table(amre_dd.ll$Fyear, amre_dd.ll$Fsite)
summary(amre_dd.ll$lat)
summary(amre_dd.ll$Fsite, amre_dd.ll$lat)
#year
# mod2 <- with(amre_dd.ll, lm(lat ~ 1))
# mod1 <- with(amre_dd.ll, lm(lat ~ Fyear-1)) #site
# summary(mod1) # View model results
# # Compare models using likelihood ratio test
# anova(mod2, mod1)
#Bootstrap function for latitude with estimated coefficients and 95% CI
iso_boot <- function(coord_df, nBoot = 1000){
for(i in 1:nBoot){
lat <- rnorm(nrow(coord_df), mean = coord_df$lat, sd = coord_df$lat_se)
lat <- scale(lat)[,1]
fit <- lm(lat ~ coord_df$Fyear-1)
if(i == 1){coefs = coef(fit)}else{coefs = rbind(coefs, coef(fit))}
}
fit_df <- data.frame(Estimate = apply(coefs, 2, mean),
LCI = apply(coefs, 2, function(x) quantile(x, 0.025)),
UCI = apply(coefs, 2, function(x) quantile(x, 0.975)))
return(fit_df)
}
#Use iso_boot(coord_df = [your df name])
Year_boot<-iso_boot(coord_df = amre_dd.ll) #Fsite
Year_boot
############
#Does breeding destination (latitude) differ for site?
# mod2 <- with(amre_dd.ll, lm(lat ~ 1))
# mod1 <- with(amre_dd.ll, lm(lat ~ Fsite)) #site
# summary(mod1) # View model results
# # Compare models using likelihood ratio test
# anova(mod2, mod1)
#Bootstrap function for latitude with estimated coefficients and 95% CI
iso_boot <- function(coord_df, nBoot = 1000){
for(i in 1:nBoot){
lat <- rnorm(nrow(coord_df), mean = coord_df$lat, sd = coord_df$lat_se)
lat <- scale(lat)[,1]
fit <- lm(lat ~ coord_df$Fsite + coord_df$Fyear -1)
if(i == 1){coefs = coef(fit)}else{coefs = rbind(coefs, coef(fit))}
}
fit_df <- data.frame(Estimate = apply(coefs, 2, mean),
LCI = apply(coefs, 2, function(x) quantile(x, 0.025)),
UCI = apply(coefs, 2, function(x) quantile(x, 0.975)))
return(fit_df)
}
#run boot
Site_boot<-iso_boot(coord_df = amre_dd.ll) #Fsite
Site_boot
############################################################
#Do the sites differ in the timing of migration?
############################################################
# Do southern breeding birds migrate first?
# mod2 <- with(amre_dd.ll, lm(lat ~ 1))
# mod1 <- with(amre_dd.ll, lm(lat ~ day.yr + Fsite-1)) #site
# summary(mod1) # View model results
# # Compare models using likelihood ratio test
# anova(mod2, mod1)
summary(amre_dd.ll$day.yr)
#Bootstrap function for latitude with estimated coefficients and 95% CI
iso_boot <- function(coord_df, nBoot = 1000){
for(i in 1:nBoot){
lat <- rnorm(nrow(coord_df), mean = coord_df$lat, sd = coord_df$lat_se)
lat <- scale(lat)[,1]
fit <- lm(coord_df$day.yr ~ lat + coord_df$Fsite + coord_df$Fyear -1)
if(i == 1){coefs = coef(fit)}else{coefs = rbind(coefs, coef(fit))}
}
fit_df <- data.frame(Estimate = apply(coefs, 2, mean),
LCI = apply(coefs, 2, function(x) quantile(x, 0.025)),
UCI = apply(coefs, 2, function(x) quantile(x, 0.975)))
return(fit_df)
}
DOY_boot<-iso_boot(coord_df = amre_dd.ll)
DOY_boot
################
# Timing by site
#Bootstrap function for latitude with estimated coefficients and 95% CI
iso_boot <- function(coord_df, nBoot = 1000){
for(i in 1:nBoot){
lat <- rnorm(nrow(coord_df), mean = coord_df$lat, sd = coord_df$lat_se)
lat <- scale(lat)[,1]
fit <- lm(coord_df$day.yr ~ lat + coord_df$Fyear -1)
if(i == 1){coefs = coef(fit)}else{coefs = rbind(coefs, coef(fit))}
}
fit_df <- data.frame(Estimate = apply(coefs, 2, mean),
LCI = apply(coefs, 2, function(x) quantile(x, 0.025)),
UCI = apply(coefs, 2, function(x) quantile(x, 0.975)))
return(fit_df)
}
###Florida
#app
amre_app_coord$Fyear<- factor(amre_app_coord$year, levels = c("2012","2013","2014"))
table(amre_app_coord$day.yr)
# amre.app<-with(amre_app_coord, lm(lat ~ day.yr))
# amre.null<-with(amre_app_coord, lm(lat ~ 1))
# # View model results
# summary(amre.app)
# # Compare models using likelihood ratio test
# anova(amre.null, amre.app)
#boot
DOY_bootFL<-iso_boot(coord_df = amre_app_coord) #Fsite
DOY_bootFL
###Louisiana
##job
# amre.job<-with(amre_job_coord, lm(lat ~ day.yr))
# amre.null<-with(amre_job_coord, lm(lat ~ 1))
# summary(amre.job) # View model results
# # Compare models using likelihood ratio test
# anova(amre.null, amre.job)
amre_job_coord$Fyear<- factor(amre_job_coord$year, levels = c("2012","2013","2014"))
table(amre_job_coord$day.yr)
##boot
DOY_bootLA<-iso_boot(coord_df = amre_job_coord) #Fsite
DOY_bootLA
###Texas
##mad
amre.mad<- with(amre_mad_coord, lm(lat ~ day.yr))
amre.null<-with(amre_mad_coord, lm(lat ~ 1))
summary(amre.mad) # View model results
# Compare models using likelihood ratio test
anova(amre.null, amre.mad)
amre_mad_coord$Fyear<- factor(amre_mad_coord$year, levels = c("2012","2013","2014"))
table(amre_mad_coord$day.yr)
##boot
DOY_bootTX<-iso_boot(coord_df = amre_mad_coord) #Fsite
DOY_bootTX
############################################################
# 3. Is passage day, relative to destination, influenced by age and sex at stopover sites?
# Date ~ site + age + sex + Lat (2 models: with and without AMRE SY for date because SY may not go to same place)
############################################################
#remove 3 AHY, 1 U unknown sex, categorize fat
nrow(amre_dd.ll)
amre_dd.ll2 <- amre_dd.ll[which(amre_dd.ll$age != 'AHY'),] #ASY=83, SY=30
nrow(amre_dd.ll2)
#Categorize fat 0/1 as lean, 2-4 as fat
table(amre_dd.ll2$fat)
amre_dd.ll2$Cond <-"unkn"
amre_dd.ll2$Cond[amre_dd.ll2$fat=="0" | amre_dd.ll2$fat=="1"] <- "LEAN"
amre_dd.ll2$Cond[amre_dd.ll2$fat=="2" | amre_dd.ll2$fat=="3"| amre_dd.ll2$fat=="4"] <- "FAT"
amre_dd.ll2$Cond<- factor(amre_dd.ll2$Cond, levels = c("LEAN","FAT"))
amre_dd.ll2$sex<- factor(amre_dd.ll2$sex, levels = c("F","M"))
amre_dd.ll2$age<- factor(amre_dd.ll2$age, levels = c("SY","ASY"))
table(amre_dd.ll2$Cond) #FAT=28, LEAN=67
table(amre_dd.ll2$Cond, amre_dd.ll2$Fsite)
table(amre_dd.ll2$Cond, amre_dd.ll2$Fyear)
table(amre_dd.ll2$age)
table(amre_dd.ll2$sex, amre_dd.ll2$Fsite)
#Bootstrap function for latitude with estimated coefficients and 95% CI
iso_boot <- function(coord_df, nBoot = 1000){
for(i in 1:nBoot){
lat <- rnorm(nrow(coord_df), mean = coord_df$lat, sd = coord_df$lat_se)
lat <- scale(lat)[,1]
fit <- lm(coord_df$day.yr ~ coord_df$age*lat +coord_df$Fsite +coord_df$Fyear -1)
if(i == 1){coefs = coef(fit)}else{coefs = rbind(coefs, coef(fit))}
}
fit_df <- data.frame(Estimate = apply(coefs, 2, mean),
LCI = apply(coefs, 2, function(x) quantile(x, 0.025)),
UCI = apply(coefs, 2, function(x) quantile(x, 0.975)))
return(fit_df)
}
#Use iso_boot(coord_df = [your df name])
Age_boot<-iso_boot(coord_df = amre_dd.ll2)
Age_boot
#by site
#Bootstrap function for latitude with estimated coefficients and 95% CI
iso_boot <- function(coord_df, nBoot = 1000){
for(i in 1:nBoot){
lat <- rnorm(nrow(coord_df), mean = coord_df$lat, sd = coord_df$lat_se)
lat <- scale(lat)[,1]
fit <- lm(coord_df$day.yr ~ coord_df$age*lat +coord_df$Fyear -1)
if(i == 1){coefs = coef(fit)}else{coefs = rbind(coefs, coef(fit))}
}
fit_df <- data.frame(Estimate = apply(coefs, 2, mean),
LCI = apply(coefs, 2, function(x) quantile(x, 0.025)),
UCI = apply(coefs, 2, function(x) quantile(x, 0.975)))
return(fit_df)
}
##
table(amre_job_coord$age, amre_job_coord$site)
amre_app_coord <- amre_app_coord[which(amre_app_coord$age != 'AHY'),] #ASY=83, SY=30
Fage_boot<-iso_boot(coord_df = amre_app_coord)
Fage_boot
Lage_boot<-iso_boot(coord_df = amre_job_coord)
Lage_boot
Tage_boot<-iso_boot(coord_df = amre_mad_coord)
Tage_boot
# ##AOV
# amre.age<- with(amre_dd.ll2, lm(day.yr ~ age + lat + Fsite))
# amre.null<-with(amre_dd.ll2, lm(day.yr ~ lat + Fsite))
# amre.null<-with(amre_dd.ll2, lm(day.yr ~ 1))
# summary(amre.age) # View model results
#Bootstrap function for latitude with estimated coefficients and 95% CI
iso_boot <- function(coord_df, nBoot = 1000){
for(i in 1:nBoot){
lat <- rnorm(nrow(coord_df), mean = coord_df$lat, sd = coord_df$lat_se)
lat <- scale(lat)[,1]
fit <- lm(coord_df$day.yr ~ coord_df$sex*lat +coord_df$Fsite +coord_df$Fyear -1)
if(i == 1){coefs = coef(fit)}else{coefs = rbind(coefs, coef(fit))}
}
fit_df <- data.frame(Estimate = apply(coefs, 2, mean),
LCI = apply(coefs, 2, function(x) quantile(x, 0.025)),
UCI = apply(coefs, 2, function(x) quantile(x, 0.975)))
return(fit_df)
}
Sex_boot<-iso_boot(coord_df = amre_dd.ll2)
Sex_boot
#by site
#Bootstrap function for latitude with estimated coefficients and 95% CI
iso_boot <- function(coord_df, nBoot = 1000){
for(i in 1:nBoot){
lat <- rnorm(nrow(coord_df), mean = coord_df$lat, sd = coord_df$lat_se)
lat <- scale(lat)[,1]
fit <- lm(coord_df$day.yr ~ coord_df$sex*lat +coord_df$Fyear -1)
if(i == 1){coefs = coef(fit)}else{coefs = rbind(coefs, coef(fit))}
}
fit_df <- data.frame(Estimate = apply(coefs, 2, mean),
LCI = apply(coefs, 2, function(x) quantile(x, 0.025)),
UCI = apply(coefs, 2, function(x) quantile(x, 0.975)))
return(fit_df)
}
##
table(amre_job_coord$sex, amre_job_coord$site)
amre_job_coord<- amre_job_coord[which(amre_job_coord$sex != 'U'),]
FSex_boot<-iso_boot(coord_df = amre_app_coord)
FSex_boot
LSex_boot<-iso_boot(coord_df = amre_job_coord)
LSex_boot
TSex_boot<-iso_boot(coord_df = amre_mad_coord)
TSex_boot
##AOV
# table(amre_job_coord$site, amre_job_coord$sex)
# #amre.null<-with(amre_dd.ll2, lm(day.yr ~ lat + Fsite))
# amre.null<-with(amre_dd.ll2, lm(day.yr ~ 1))
# #summary(amre.sex) # View model results
# # Compare models using likelihood ratio test
# anova(amre.null, amre.sex)
############################################################
# 4. Does passage day and/ or energetic condition, relative to destination, vary with dC13?
#Day of year ~ winter environment (δ13Cc) * Breeding latitude + Site + Year
#Energetic condition (lean or fat) ~ winter environment + Breeding latitude + Site + Year
############################################################
names(amre_dd.ll)
#have to remove NAs?
summary(amre_dd.ll$cc)
summary(amre_dd.ll$Cond)
#Bootstrap function for latitude with estimated coefficients and 95% CI
iso_boot <- function(coord_df, nBoot = 1000){
for(i in 1:nBoot){
lat <- rnorm(nrow(coord_df), mean = coord_df$lat, sd = coord_df$lat_se)
lat <- scale(lat)[,1]
fit <- lm(coord_df$day.yr ~ coord_df$cc*lat + coord_df$Fsite + coord_df$Fyear -1) #make sure attributes attached
if(i == 1){coefs = coef(fit)}else{coefs = rbind(coefs, coef(fit))}
}
fit_df <- data.frame(Estimate = apply(coefs, 2, mean),
LCI = apply(coefs, 2, function(x) quantile(x, 0.025)),
UCI = apply(coefs, 2, function(x) quantile(x, 0.975)))
return(fit_df)
}
CC_boot<-iso_boot(coord_df = amre_dd.ll)
CC_boot
###at each site
iso_boot <- function(coord_df, nBoot = 1000){
for(i in 1:nBoot){
lat <- rnorm(nrow(coord_df), mean = coord_df$lat, sd = coord_df$lat_se)
lat <- scale(lat)[,1]
fit <- lm(coord_df$day.yr ~ coord_df$cc*lat + coord_df$Fyear -1) #make sure attributes attached
if(i == 1){coefs = coef(fit)}else{coefs = rbind(coefs, coef(fit))}
}
fit_df <- data.frame(Estimate = apply(coefs, 2, mean),
LCI = apply(coefs, 2, function(x) quantile(x, 0.025)),
UCI = apply(coefs, 2, function(x) quantile(x, 0.975)))
return(fit_df)
}
FCC_boot<-iso_boot(coord_df = amre_app_coord)
FCC_boot
LCC_boot<-iso_boot(coord_df = amre_job_coord)
LCC_boot
TCC_boot<-iso_boot(coord_df = amre_mad_coord)
TCC_boot
#####Condition
#Bootstrap function for latitude with estimated coefficients and 95% CI
iso_boot <- function(coord_df, nBoot = 1000){
for(i in 1:nBoot){
lat <- rnorm(nrow(coord_df), mean = coord_df$lat, sd = coord_df$lat_se)
lat <- scale(lat)[,1]
fit <- lm(coord_df$Cond ~ coord_df$cc*lat + coord_df$Fsite + coord_df$Fyear -1) #make sure attributes attached
if(i == 1){coefs = coef(fit)}else{coefs = rbind(coefs, coef(fit))}
}
fit_df <- data.frame(Estimate = apply(coefs, 2, mean),
LCI = apply(coefs, 2, function(x) quantile(x, 0.025)),
UCI = apply(coefs, 2, function(x) quantile(x, 0.975)))
return(fit_df)
}
Cond_boot<-iso_boot(coord_df = amre_dd.ll)
Cond_boot
###at each site
iso_boot <- function(coord_df, nBoot = 1000){
for(i in 1:nBoot){
lat <- rnorm(nrow(coord_df), mean = coord_df$lat, sd = coord_df$lat_se)
lat <- scale(lat)[,1]
fit <- lm(coord_df$Cond ~ coord_df$cc*lat + coord_df$Fyear -1) #make sure attributes attached
if(i == 1){coefs = coef(fit)}else{coefs = rbind(coefs, coef(fit))}
}
fit_df <- data.frame(Estimate = apply(coefs, 2, mean),
LCI = apply(coefs, 2, function(x) quantile(x, 0.025)),
UCI = apply(coefs, 2, function(x) quantile(x, 0.975)))
return(fit_df)
}
FCC_boot<-iso_boot(coord_df = amre_app_coord)
FCC_boot
LCC_boot<-iso_boot(coord_df = amre_job_coord)
LCC_boot
TCC_boot<-iso_boot(coord_df = amre_mad_coord)
TCC_boot
#############################################################################
#########################################################
##OVEN ASSIGN
#########################################################
# dat$date <- as.Date(dat$date, format = "%Y-%m-%d")
# oven_dd <- dat %>% filter(species == "OVEN")
# ## Subset OVEN data by site
# oven_app_dd <- oven_dd %>% filter(site == "APP"& !is.na(dd))
# oven_job_dd <- oven_dd %>% filter(site == "JOB"& !is.na(dd))
# oven_mad_dd <- oven_dd %>% filter(site == "MAD"& !is.na(dd))
# ## Assign individuals from each site
# oven_app_assign <- iso_assign(dd = oven_app_dd$dd, df_base = oven_base$df.ahy, lat = oven_base$y, lon = oven_base$x, names = oven_app_dd$band.no)
# oven_job_assign <- iso_assign(dd = oven_job_dd$dd, df_base = oven_base$df.ahy, lat = oven_base$y, lon = oven_base$x, names = oven_job_dd$band.no)
# oven_mad_assign <- iso_assign(dd = oven_mad_dd$dd, df_base = oven_base$df.ahy, lat = oven_base$y, lon = oven_base$x, names = oven_mad_dd$band.no)
# #add weighteing by abundnace
# oven_app_assign <- abun_assign(iso_data = oven_app_assign, rel_abun = oven_base$rel.abun, iso_weight = -0.7, abun_weight = 0)
# oven_job_assign <- abun_assign(iso_data = oven_job_assign, rel_abun = oven_base$rel.abun, iso_weight = -0.7, abun_weight = 0)
# oven_mad_assign <- abun_assign(iso_data = oven_mad_assign, rel_abun = oven_base$rel.abun, iso_weight = -0.7, abun_weight = 0)
# ## Create dataframe with assignment results
# ##convert to a matrix to rearange
# oven_app_mat <- matrix(oven_app_assign$wght_origin, nrow = nrow(oven_base), ncol = length(oven_app_dd$dd), byrow = FALSE)
# oven_job_mat <- matrix(oven_job_assign$wght_origin, nrow = nrow(oven_base), ncol = length(oven_job_dd$dd), byrow = FALSE)
# oven_mad_mat <- matrix(oven_mad_assign$wght_origin, nrow = nrow(oven_base), ncol = length(oven_mad_dd$dd), byrow = FALSE)
# oven_assign <- data.frame(Latitude = oven_base$y,
# Longitude = oven_base$x,
# app_origin = apply(oven_app_mat, 1, sum)/ncol(oven_app_mat),
# job_origin = apply(oven_job_mat, 1, sum)/ncol(oven_job_mat),
# mad_origin = apply(oven_mad_mat, 1, sum)/ncol(oven_mad_mat))
# ##plot assignment from each site
# ## Write results to ~Results
# write.csv(oven_assign, file = "Results/oven_assign.csv", row.names = FALSE)
#
# ##Use to measure mean lat long/ site, without error
# #loop through individuals from a site, in columns
# #app
# oven_app_coord <- iso.assign2::wght_coord(summ = oven_app_assign, iso = FALSE) %>% rename(band.no = indv) %>%
# left_join(., oven_app_dd)
# #job
# oven_job_coord <- iso.assign2::wght_coord(summ = oven_job_assign, iso = FALSE) %>% rename(band.no = indv) %>%
# left_join(., oven_job_dd)
# #mad
# oven_mad_coord <- iso.assign2::wght_coord(summ = oven_mad_assign, iso = FALSE) %>% rename(band.no = indv) %>%
# left_join(., oven_mad_dd)
# names(oven_app_coord)
# names(oven_job_coord)
# names(oven_mad_coord)
#Merge file with attributes and mean lat long for all OVEN
oven_dd.ll<-rbind(oven_app_coord,oven_job_coord)
oven_dd.ll<-rbind(oven_dd.ll,oven_mad_coord)
nrow(oven_dd.ll) #150
names(oven_dd.ll)
names(oven_mad_coord)
############################################################
# Questions:
# 1. Does destination vary among sites? Lat ~ site
############################################################
#change order of levels for sites
oven_dd.ll$Fsite<- factor(oven_dd.ll$site, levels = c("MAD","JOB","APP"), labels=c("Texas","Louisiana","Florida"))
#summary(oven_dd.ll)
table(oven_dd.ll$site)
table(oven_dd.ll$Fsite)
table(oven_dd.ll$site, oven_dd.ll$age)
table(oven_dd.ll$site, oven_dd.ll$sex)
table(oven_dd.ll$sex)
summary(oven_dd.ll$year)
oven_dd.ll$Fyear<- factor(oven_dd.ll$year, levels = c("2012","2013","2014"))
table(oven_dd.ll$Fyear)
table(oven_dd.ll$Fyear, oven_dd.ll$Fsite)
summary(oven_dd.ll$lat)
summary(oven_dd.ll$Fsite, oven_dd.ll$lat)
oven_dd.ll$Cond <-"unkn"
oven_dd.ll$Cond[oven_dd.ll$fat=="0" | oven_dd.ll$fat=="1"] <- "LEAN"
oven_dd.ll$Cond[oven_dd.ll$fat=="2" | oven_dd.ll$fat=="3"| oven_dd.ll$fat=="4"] <- "FAT"
oven_dd.ll$Cond<- factor(oven_dd.ll$Cond, levels = c("LEAN","FAT"))
table(oven_dd.ll$site)
table(oven_dd.ll$site, oven_dd.ll$Cond)
####First
##Does latitude vary among years?
# mod2 <- with(oven_dd.ll, lm(lat ~ 1))
# mod1 <- with(oven_dd.ll, lm(lat ~ Fyear-1)) #site
# summary(mod1) # View model results
# # Compare models using likelihood ratio test
# anova(mod2, mod1)
names(oven_dd.ll)
#Bootstrap function for latitude with estimated coefficients and 95% CI
iso_boot <- function(coord_df, nBoot = 1000){
for(i in 1:nBoot){
lat <- rnorm(nrow(coord_df), mean = coord_df$lat, sd = coord_df$lat_se)
lat <- scale(lat)[,1]
fit <- lm(lat ~ coord_df$Fyear-1)
if(i == 1){coefs = coef(fit)}else{coefs = rbind(coefs, coef(fit))}
}
fit_df <- data.frame(Estimate = apply(coefs, 2, mean),
LCI = apply(coefs, 2, function(x) quantile(x, 0.025)),
UCI = apply(coefs, 2, function(x) quantile(x, 0.975)))
return(fit_df)
}
#Use iso_boot(coord_df = [your df name])
Year_boot<-iso_boot(coord_df = oven_dd.ll) #Fsite
Year_boot
############
#Does breeding destination (latitude) differ for site?
table(oven_dd.ll$Fsite, oven_dd.ll$lat)
# mod2 <- with(oven_dd.ll, lm(lat ~ 1))
# mod1 <- with(oven_dd.ll, lm(lat ~ Fsite -1)) #site
# summary(mod1) # View model results
# # Compare models using likelihood ratio test
# anova(mod2, mod1)
#Bootstrap function for latitude with estimated coefficients and 95% CI
iso_boot <- function(coord_df, nBoot = 1000){
for(i in 1:nBoot){
lat <- rnorm(nrow(coord_df), mean = coord_df$lat, sd = coord_df$lat_se)
lat <- scale(lat)[,1]
fit <- lm(lat ~ coord_df$Fsite + coord_df$Fyear -1)
if(i == 1){coefs = coef(fit)}else{coefs = rbind(coefs, coef(fit))}
}
fit_df <- data.frame(Estimate = apply(coefs, 2, mean),
LCI = apply(coefs, 2, function(x) quantile(x, 0.025)),
UCI = apply(coefs, 2, function(x) quantile(x, 0.975)))
return(fit_df)
}
#run boot
Site_boot<-iso_boot(coord_df = oven_dd.ll) #Fsite
Site_boot
############################################################
#2. Do the sites differ in the timing of migration?
############################################################
# Do southern breeding birds migrate first?
# mod2 <- with(oven_dd.ll, lm(lat ~ 1))
# mod1 <- with(oven_dd.ll, lm(lat ~ day.yr + Fsite-1)) #site
# summary(mod1) # View model results
# # Compare models using likelihood ratio test
# anova(mod2, mod1)
summary(oven_dd.ll$day.yr)
table(oven_dd.ll$Fsite ,oven_dd.ll$day.yr)
#Bootstrap function for latitude with estimated coefficients and 95% CI
iso_boot <- function(coord_df, nBoot = 1000){
for(i in 1:nBoot){
lat <- rnorm(nrow(coord_df), mean = coord_df$lat, sd = coord_df$lat_se)
lat <- scale(lat)[,1]
fit <- lm(coord_df$day.yr ~ lat + coord_df$Fsite + coord_df$Fyear -1)
if(i == 1){coefs = coef(fit)}else{coefs = rbind(coefs, coef(fit))}
}
fit_df <- data.frame(Estimate = apply(coefs, 2, mean),
LCI = apply(coefs, 2, function(x) quantile(x, 0.025)),
UCI = apply(coefs, 2, function(x) quantile(x, 0.975)))
return(fit_df)
}
DOY_boot<-iso_boot(coord_df = oven_dd.ll)
DOY_boot
################
# Timing by site
#Bootstrap function for latitude with estimated coefficients and 95% CI
iso_boot <- function(coord_df, nBoot = 1000){
for(i in 1:nBoot){
lat <- rnorm(nrow(coord_df), mean = coord_df$lat, sd = coord_df$lat_se)
lat <- scale(lat)[,1]
fit <- lm(coord_df$day.yr ~ lat + coord_df$Fyear -1)
if(i == 1){coefs = coef(fit)}else{coefs = rbind(coefs, coef(fit))}
}
fit_df <- data.frame(Estimate = apply(coefs, 2, mean),
LCI = apply(coefs, 2, function(x) quantile(x, 0.025)),
UCI = apply(coefs, 2, function(x) quantile(x, 0.975)))
return(fit_df)
}
###Florida
#app
# oven_app_coord$Fyear<- factor(oven_app_coord$year, levels = c("2012","2013","2014"))
# # table(oven_app_coord$day.yr)
# oven.app<-with(oven_app_coord, lm(lat ~ day.yr))
# oven.null<-with(oven_app_coord, lm(lat ~ 1))
# # View model results
# summary(oven.app)
# # Compare models using likelihood ratio test
# anova(oven.null, oven.app)
#boot
DOY_bootFL<-iso_boot(coord_df = oven_app_coord) #Fsite
DOY_bootFL
###Louisiana
##job
# oven.job<-with(oven_job_coord, lm(lat ~ day.yr))
# oven.null<-with(oven_job_coord, lm(lat ~ 1))
# summary(oven.job) # View model results
# # Compare models using likelihood ratio test
# anova(oven.null, oven.job)
oven_job_coord$Fyear<- factor(oven_job_coord$year, levels = c("2012","2013","2014"))
# table(oven_job_coord$day.yr)
##boot
DOY_bootLA<-iso_boot(coord_df = oven_job_coord) #Fsite
DOY_bootLA
###Texas
##mad
# oven.mad<- with(oven_mad_coord, lm(lat ~ day.yr))
# oven.null<-with(oven_mad_coord, lm(lat ~ 1))
# summary(oven.mad) # View model results
# # Compare models using likelihood ratio test
# anova(oven.null, oven.mad)
oven_mad_coord$Fyear<- factor(oven_mad_coord$year, levels = c("2012","2013","2014"))
table(oven_mad_coord$day.yr)
##boot
DOY_bootTX<-iso_boot(coord_df = oven_mad_coord) #Fsite
DOY_bootTX
############################################################
# 3. Is passage day, relative to destination, influenced by age and sex at stopover sites?
# Date ~ site + age + sex + Lat (2 models: with and without oven SY for date because SY may not go to same place)
############################################################
#remove 3 AHY, 1 U unknown sex, categorize fat
nrow(oven_dd.ll)
oven_dd.ll2 <- oven_dd.ll[which(oven_dd.ll$age != 'AHY'),] #ASY=83, SY=30
nrow(oven_dd.ll2)
table(oven_dd.ll2$age)
#Bootstrap function for latitude with estimated coefficients and 95% CI
iso_boot <- function(coord_df, nBoot = 1000){
for(i in 1:nBoot){
lat <- rnorm(nrow(coord_df), mean = coord_df$lat, sd = coord_df$lat_se)
lat <- scale(lat)[,1]
fit <- lm(coord_df$day.yr ~ coord_df$age*lat +coord_df$Fsite +coord_df$Fyear -1)
if(i == 1){coefs = coef(fit)}else{coefs = rbind(coefs, coef(fit))}
}
fit_df <- data.frame(Estimate = apply(coefs, 2, mean),
LCI = apply(coefs, 2, function(x) quantile(x, 0.025)),
UCI = apply(coefs, 2, function(x) quantile(x, 0.975)))
return(fit_df)
}
#Use iso_boot(coord_df = [your df name])
Age_boot<-iso_boot(coord_df = oven_dd.ll2)
Age_boot
#by site
#Bootstrap function for latitude with estimated coefficients and 95% CI
iso_boot <- function(coord_df, nBoot = 1000){
for(i in 1:nBoot){
lat <- rnorm(nrow(coord_df), mean = coord_df$lat, sd = coord_df$lat_se)
lat <- scale(lat)[,1]
fit <- lm(coord_df$day.yr ~ coord_df$age*lat +coord_df$Fyear -1)
if(i == 1){coefs = coef(fit)}else{coefs = rbind(coefs, coef(fit))}
}
fit_df <- data.frame(Estimate = apply(coefs, 2, mean),
LCI = apply(coefs, 2, function(x) quantile(x, 0.025)),
UCI = apply(coefs, 2, function(x) quantile(x, 0.975)))
return(fit_df)
}
##
table(oven_job_coord$age, oven_job_coord$site)
oven_app_coord <- oven_app_coord[which(oven_app_coord$age != 'AHY'),] #ASY=83, SY=30
oven_job_coord <- oven_job_coord[which(oven_job_coord$age != 'AHY'),] #ASY=83, SY=30
oven_mad_coord <- oven_mad_coord[which(oven_mad_coord$age != 'AHY'),] #ASY=83, SY=30
table(oven_app_coord$age)
table(oven_job_coord$age)
table(oven_mad_coord$age)
Fage_boot<-iso_boot(coord_df = oven_app_coord)
Fage_boot
Lage_boot<-iso_boot(coord_df = oven_job_coord)
Lage_boot
Tage_boot<-iso_boot(coord_df = oven_mad_coord)
Tage_boot
############################################################
# 4. Does passage day and/ or energetic condition, relative to destination, vary with dC13?
#Day of year ~ winter environment (δ13Cc) * Breeding latitude + Site + Year
#Energetic condition (lean or fat) ~ winter environment + Breeding latitude + Site + Year
############################################################
names(oven_dd.ll)
#have to remove NAs?
nrow(oven_dd.ll)
summary(oven_dd.ll$cc)
summary(oven_dd.ll$Cond)
#Bootstrap function for latitude with estimated coefficients and 95% CI
iso_boot <- function(coord_df, nBoot = 1000){
for(i in 1:nBoot){
lat <- rnorm(nrow(coord_df), mean = coord_df$lat, sd = coord_df$lat_se)
lat <- scale(lat)[,1]
fit <- lm(coord_df$day.yr ~ coord_df$cc*lat + coord_df$Fsite + coord_df$Fyear -1) #make sure attributes attached
if(i == 1){coefs = coef(fit)}else{coefs = rbind(coefs, coef(fit))}
}
fit_df <- data.frame(Estimate = apply(coefs, 2, mean),
LCI = apply(coefs, 2, function(x) quantile(x, 0.025)),
UCI = apply(coefs, 2, function(x) quantile(x, 0.975)))
return(fit_df)
}
CC_boot<-iso_boot(coord_df = oven_dd.ll)
CC_boot
###at each site
iso_boot <- function(coord_df, nBoot = 1000){
for(i in 1:nBoot){
lat <- rnorm(nrow(coord_df), mean = coord_df$lat, sd = coord_df$lat_se)
lat <- scale(lat)[,1]
fit <- lm(coord_df$day.yr ~ coord_df$cc*lat + coord_df$Fyear -1) #make sure attributes attached
if(i == 1){coefs = coef(fit)}else{coefs = rbind(coefs, coef(fit))}
}
fit_df <- data.frame(Estimate = apply(coefs, 2, mean),
LCI = apply(coefs, 2, function(x) quantile(x, 0.025)),
UCI = apply(coefs, 2, function(x) quantile(x, 0.975)))
return(fit_df)
}
FCC_boot<-iso_boot(coord_df = oven_app_coord)
FCC_boot
LCC_boot<-iso_boot(coord_df = oven_job_coord)
LCC_boot
TCC_boot<-iso_boot(coord_df = oven_mad_coord)
TCC_boot
#####Condition
#Bootstrap function for latitude with estimated coefficients and 95% CI
class(oven_dd.ll$fat)
#
iso_boot <- function(coord_df, nBoot = 1000){
for(i in 1:nBoot){
lat <- rnorm(nrow(coord_df), mean = coord_df$lat, sd = coord_df$lat_se)
lat <- scale(lat)[,1]
fit <- lm(coord_df$fat ~ coord_df$cc*lat + coord_df$Fsite + coord_df$Fyear -1) #make sure attributes attached
if(i == 1){coefs = coef(fit)}else{coefs = rbind(coefs, coef(fit))}
}
fit_df <- data.frame(Estimate = apply(coefs, 2, mean),
LCI = apply(coefs, 2, function(x) quantile(x, 0.025)),
UCI = apply(coefs, 2, function(x) quantile(x, 0.975)))
return(fit_df)
}
Cond_boot<-iso_boot(coord_df = oven_dd.ll)
Cond_boot
###at each site
iso_boot <- function(coord_df, nBoot = 1000){
for(i in 1:nBoot){
lat <- rnorm(nrow(coord_df), mean = coord_df$lat, sd = coord_df$lat_se)
lat <- scale(lat)[,1]
fit <- lm(coord_df$Cond ~ coord_df$cc*lat + coord_df$Fyear -1) #make sure attributes attached
if(i == 1){coefs = coef(fit)}else{coefs = rbind(coefs, coef(fit))}
}
fit_df <- data.frame(Estimate = apply(coefs, 2, mean),
LCI = apply(coefs, 2, function(x) quantile(x, 0.025)),
UCI = apply(coefs, 2, function(x) quantile(x, 0.975)))
return(fit_df)
}
FCC_boot<-iso_boot(coord_df = oven_app_coord)
FCC_boot
LCC_boot<-iso_boot(coord_df = oven_job_coord)
LCC_boot
TCC_boot<-iso_boot(coord_df = oven_mad_coord)
TCC_boot
########################################################
##WOTH ASSIGN
########################################################
# woth_dd <- dat %>% filter(species == "WOTH")
# ## Subset WOTH data by site
# woth_app_dd <- woth_dd %>% filter(site == "APP"& !is.na(dd))
# woth_job_dd <- woth_dd %>% filter(site == "JOB"& !is.na(dd))
# woth_mad_dd <- woth_dd %>% filter(site == "MAD"& !is.na(dd))
# ## Assign individuals from each site
# woth_app_assign <- iso_assign(dd = woth_app_dd$dd, df_base = woth_base$df.ahy, lat = woth_base$y, lon = woth_base$x, names = woth_app_dd$band.no)
# woth_job_assign <- iso_assign(dd = woth_job_dd$dd, df_base = woth_base$df.ahy, lat = woth_base$y, lon = woth_base$x, names = woth_job_dd$band.no)
# woth_mad_assign <- iso_assign(dd = woth_mad_dd$dd, df_base = woth_base$df.ahy, lat = woth_base$y, lon = woth_base$x, names = woth_mad_dd$band.no)
# #add weighteing by abundnace
# woth_app_assign <- abun_assign(iso_data = woth_app_assign, rel_abun = woth_base$rel.abun, iso_weight = -0.7, abun_weight = 0)
# woth_job_assign <- abun_assign(iso_data = woth_job_assign, rel_abun = woth_base$rel.abun, iso_weight = -0.7, abun_weight = 0)
# woth_mad_assign <- abun_assign(iso_data = woth_mad_assign, rel_abun = woth_base$rel.abun, iso_weight = -0.7, abun_weight = 0)
# ## Create dataframe with assignment results
# ##convert to a matrix to rearange
# woth_app_mat <- matrix(woth_app_assign$wght_origin, nrow = nrow(woth_base), ncol = length(woth_app_dd$dd), byrow = FALSE)
# woth_job_mat <- matrix(woth_job_assign$wght_origin, nrow = nrow(woth_base), ncol = length(woth_job_dd$dd), byrow = FALSE)
# woth_mad_mat <- matrix(woth_mad_assign$wght_origin, nrow = nrow(woth_base), ncol = length(woth_mad_dd$dd), byrow = FALSE)
# woth_assign <- data.frame(Latitude = woth_base$y,
# Longitude = woth_base$x,
# app_origin = apply(woth_app_mat, 1, sum)/ncol(woth_app_mat),
# job_origin = apply(woth_job_mat, 1, sum)/ncol(woth_job_mat),
# mad_origin = apply(woth_mad_mat, 1, sum)/ncol(woth_mad_mat))
# ## Write results to ~Results
# write.csv(woth_assign, file = "Results/woth_assign.csv", row.names = FALSE)
#loop through individuals from a site, in columns
#app
# woth_app_coord <- iso.assign2::wght_coord(summ = woth_app_assign, iso = FALSE) %>% rename(band.no = indv) %>%
# left_join(., woth_app_dd)
# #job
# woth_job_coord <- iso.assign2::wght_coord(summ = woth_job_assign, iso = FALSE) %>% rename(band.no = indv) %>%
# left_join(., woth_job_dd)
# #mad
# woth_mad_coord <- iso.assign2::wght_coord(summ = woth_mad_assign, iso = FALSE) %>% rename(band.no = indv) %>%
# left_join(., woth_mad_dd)
nrow(woth_app_coord)
nrow(woth_job_coord)
nrow(woth_mad_coord)
names(woth_app_coord)
names(woth_job_coord)
names(woth_mad_coord)
#Merge file with attributes and mean lat long for all WOTH
woth_dd.ll<-rbind(woth_app_coord,woth_job_coord)
woth_dd.ll<-rbind(woth_dd.ll,woth_mad_coord)
nrow(woth_dd.ll) #184
summary(woth_dd.ll)
#Categorize fat 0/1 as lean, 2-4 as fat
table(woth_dd.ll$fat)
woth_dd.ll$Cond[woth_dd.ll$fat=="0" | woth_dd.ll$fat=="1"] <- "LEAN"
woth_dd.ll$Cond[woth_dd.ll$fat=="2" | woth_dd.ll$fat=="3"| woth_dd.ll$fat=="4"] <- "FAT"
table(woth_dd.ll$Cond) #FAT=28, LEAN=67
woth_dd.ll$Cond<-as.factor(woth_dd.ll$Cond)
woth_job_coord$Fyear<- factor(woth_job_coord$year, levels = c("2012","2013","2014"))
#change order of levels for sites
woth_dd.ll$Fsite<- factor(woth_dd.ll$site, levels = c("MAD","JOB","APP"), labels=c("Texas","Louisiana","Florida"))
table(woth_dd.ll$fat)
table(woth_dd.ll$Fsite)
table(woth_dd.ll$year)
table(woth_dd.ll$age)
table(woth_dd.ll$sex)
table(woth_dd.ll$Cond)
table(woth_dd.ll$Fsite, woth_dd.ll$age)
summary(woth_dd.ll)
table(woth_dd.ll$Cond, woth_dd.ll$Fsite)
table(woth_dd.ll$lat, woth_dd.ll$Fsite)
#There are no differences in latitude between sites
#Bootstrap function for latitude with estimated coefficients and 95% CI
iso_boot <- function(coord_df, nBoot = 1000){
for(i in 1:nBoot){
lat <- rnorm(nrow(coord_df), mean = coord_df$lat, sd = coord_df$lat_se)
lat <- scale(lat)[,1]
fit <- lm(lat ~ coord_df$Fyear-1)
if(i == 1){coefs = coef(fit)}else{coefs = rbind(coefs, coef(fit))}
}
fit_df <- data.frame(Estimate = apply(coefs, 2, mean),
LCI = apply(coefs, 2, function(x) quantile(x, 0.025)),
UCI = apply(coefs, 2, function(x) quantile(x, 0.975)))
return(fit_df)
}
#Use iso_boot(coord_df = [your df name])
Year_boot<-iso_boot(coord_df = woth_dd.ll) #Fsite
Year_boot
############
#Does breeding destination (latitude) differ for site?
table(oven_dd.ll$Fsite, oven_dd.ll$lat)
#Does breeding destination (latitude) differ for site?
# mod2 <- with(woth_dd.ll, lm(lat ~ 1))
# mod1 <- with(woth_dd.ll, lm(lat ~ Fsite))
# summary(mod1) # View model results
# # Compare models using likelihood ratio test
# anova(mod2, mod1)
#Bootstrap function for latitude with estimated coefficients and 95% CI
iso_boot <- function(coord_df, nBoot = 1000){
for(i in 1:nBoot){
lat <- rnorm(nrow(coord_df), mean = coord_df$lat, sd = coord_df$lat_se)
lat <- scale(lat)[,1]
fit <- lm(lat ~ coord_df$Fsite -1) #+ coord_df$Fyear
if(i == 1){coefs = coef(fit)}else{coefs = rbind(coefs, coef(fit))}
}
fit_df <- data.frame(Estimate = apply(coefs, 2, mean),
LCI = apply(coefs, 2, function(x) quantile(x, 0.025)),
UCI = apply(coefs, 2, function(x) quantile(x, 0.975)))
return(fit_df)
}
#run boot
Site_boot<-iso_boot(coord_df = woth_dd.ll) #Fsite
Site_boot
############################################################
#2. Do the sites differ in the timing of migration?
############################################################
# Do southern breeding birds migrate first?
# mod2 <- with(woth_dd.ll, lm(lat ~ 1))
# mod1 <- with(woth_dd.ll, lm(lat ~ day.yr + Fsite-1)) #site
# summary(mod1) # View model results
# # Compare models using likelihood ratio test
# anova(mod2, mod1)
# summary(woth_dd.ll$day.yr)
table(woth_dd.ll$Fsite ,woth_dd.ll$day.yr)
#Bootstrap function for latitude with estimated coefficients and 95% CI
iso_boot <- function(coord_df, nBoot = 1000){
for(i in 1:nBoot){
lat <- rnorm(nrow(coord_df), mean = coord_df$lat, sd = coord_df$lat_se)
lat <- scale(lat)[,1]
fit <- lm(coord_df$day.yr ~ lat + coord_df$Fsite -1) # + coord_df$Fyear
if(i == 1){coefs = coef(fit)}else{coefs = rbind(coefs, coef(fit))}
}
fit_df <- data.frame(Estimate = apply(coefs, 2, mean),
LCI = apply(coefs, 2, function(x) quantile(x, 0.025)),
UCI = apply(coefs, 2, function(x) quantile(x, 0.975)))
return(fit_df)
}
DOY_boot<-iso_boot(coord_df = woth_dd.ll)
DOY_boot
################
# Timing by site
#Bootstrap function for latitude with estimated coefficients and 95% CI
iso_boot <- function(coord_df, nBoot = 1000){
for(i in 1:nBoot){
lat <- rnorm(nrow(coord_df), mean = coord_df$lat, sd = coord_df$lat_se)
lat <- scale(lat)[,1]
fit <- lm(coord_df$day.yr ~ lat + coord_df$Fyear -1)
if(i == 1){coefs = coef(fit)}else{coefs = rbind(coefs, coef(fit))}
}
fit_df <- data.frame(Estimate = apply(coefs, 2, mean),
LCI = apply(coefs, 2, function(x) quantile(x, 0.025)),
UCI = apply(coefs, 2, function(x) quantile(x, 0.975)))
return(fit_df)
}
###Florida
#app
# woth_app_coord$Fyear<- factor(woth_app_coord$year, levels = c("2012","2013","2014"))
# # table(woth_app_coord$day.yr)
# woth.app<-with(woth_app_coord, lm(lat ~ day.yr))
# woth.null<-with(woth_app_coord, lm(lat ~ 1))
# # View model results
# summary(woth.app)
# # Compare models using likelihood ratio test
# anova(woth.null, woth.app)
#boot
DOY_bootFL<-iso_boot(coord_df = woth_app_coord) #Fsite
DOY_bootFL
###Louisiana
##job
# woth.job<-with(woth_job_coord, lm(lat ~ day.yr))
# woth.null<-with(woth_job_coord, lm(lat ~ 1))
# summary(woth.job) # View model results
# # Compare models using likelihood ratio test
# anova(woth.null, woth.job)
woth_job_coord$Fyear<- factor(woth_job_coord$year, levels = c("2012","2013","2014"))
# table(woth_job_coord$day.yr)
##boot
DOY_bootLA<-iso_boot(coord_df = woth_job_coord) #Fsite
DOY_bootLA
###Texas
##mad
# woth.mad<- with(woth_mad_coord, lm(lat ~ day.yr))
# woth.null<-with(woth_mad_coord, lm(lat ~ 1))
# summary(woth.mad) # View model results
# # Compare models using likelihood ratio test
# anova(woth.null, woth.mad)
woth_mad_coord$Fyear<- factor(woth_mad_coord$year, levels = c("2012","2013","2014"))
table(woth_mad_coord$Fyear)
##boot
DOY_bootTX<-iso_boot(coord_df = woth_mad_coord) #Fsite
DOY_bootTX
############################################################
# 3. Is passage day, relative to destination, influenced by age and sex at stopover sites?
# Date ~ site + age + sex + Lat (2 models: with and without woth SY for date because SY may not go to same place)
############################################################
#remove 3 AHY, 1 U unknown sex, categorize fat
# nrow(woth_dd.ll)
woth_dd.ll2 <- woth_dd.ll[which(woth_dd.ll$age != 'AHY'),] #ASY=83, SY=30
names(woth_dd.ll2)
woth_dd.ll2$Fyear<- factor(woth_dd.ll2$year, levels = c("2012","2013","2014"))
# table(woth_dd.ll2$age)
#Bootstrap function for latitude with estimated coefficients and 95% CI
iso_boot <- function(coord_df, nBoot = 1000){
for(i in 1:nBoot){
lat <- rnorm(nrow(coord_df), mean = coord_df$lat, sd = coord_df$lat_se)
lat <- scale(lat)[,1]
fit <- lm(coord_df$day.yr ~ coord_df$age*lat +coord_df$Fsite +coord_df$Fyear -1)
if(i == 1){coefs = coef(fit)}else{coefs = rbind(coefs, coef(fit))}
}
fit_df <- data.frame(Estimate = apply(coefs, 2, mean),
LCI = apply(coefs, 2, function(x) quantile(x, 0.025)),
UCI = apply(coefs, 2, function(x) quantile(x, 0.975)))
return(fit_df)
}
#Use iso_boot(coord_df = [your df name])
Age_boot<-iso_boot(coord_df = woth_dd.ll2)
Age_boot
#by site
#Bootstrap function for latitude with estimated coefficients and 95% CI
iso_boot <- function(coord_df, nBoot = 1000){
for(i in 1:nBoot){
lat <- rnorm(nrow(coord_df), mean = coord_df$lat, sd = coord_df$lat_se)
lat <- scale(lat)[,1]
fit <- lm(coord_df$day.yr ~ coord_df$age*lat +coord_df$Fyear -1)
if(i == 1){coefs = coef(fit)}else{coefs = rbind(coefs, coef(fit))}
}
fit_df <- data.frame(Estimate = apply(coefs, 2, mean),
LCI = apply(coefs, 2, function(x) quantile(x, 0.025)),
UCI = apply(coefs, 2, function(x) quantile(x, 0.975)))
return(fit_df)
}
##
table(woth_job_coord$age, woth_job_coord$site)
woth_app_coord <- woth_app_coord[which(woth_app_coord$age != 'AHY'),] #ASY=83, SY=30
woth_job_coord <- woth_job_coord[which(woth_job_coord$age != 'AHY'),] #ASY=83, SY=30
woth_mad_coord <- woth_mad_coord[which(woth_mad_coord$age != 'AHY'),] #ASY=83, SY=30
table(woth_app_coord$age)
table(woth_job_coord$age)
table(woth_mad_coord$age)
Lage_boot<-iso_boot(coord_df = woth_job_coord)
Lage_boot
Tage_boot<-iso_boot(coord_df = woth_mad_coord)
Tage_boot
############################################################
# 4. Does passage day and/ or energetic condition, relative to destination, vary with dC13?
#Day of year ~ winter environment (δ13Cc) * Breeding latitude + Site + Year
#Energetic condition (lean or fat) ~ winter environment + Breeding latitude + Site + Year
############################################################
names(woth_dd.ll)
#have to remove NAs?
nrow(woth_dd.ll)
summary(woth_dd.ll$cc)
summary(woth_dd.ll$Cond)
#Bootstrap function for latitude with estimated coefficients and 95% CI
woth_dd.ll$Fyear<- factor(woth_dd.ll$year, levels = c("2012","2013","2014"))
iso_boot <- function(coord_df, nBoot = 1000){
for(i in 1:nBoot){
lat <- rnorm(nrow(coord_df), mean = coord_df$lat, sd = coord_df$lat_se)
lat <- scale(lat)[,1]
fit <- lm(coord_df$day.yr ~ coord_df$cc*lat + coord_df$Fsite + coord_df$Fyear -1) #make sure attributes attached
if(i == 1){coefs = coef(fit)}else{coefs = rbind(coefs, coef(fit))}
}
fit_df <- data.frame(Estimate = apply(coefs, 2, mean),
LCI = apply(coefs, 2, function(x) quantile(x, 0.025)),
UCI = apply(coefs, 2, function(x) quantile(x, 0.975)))
return(fit_df)
}
CC_boot<-iso_boot(coord_df = woth_dd.ll)
CC_boot
###at each site
iso_boot <- function(coord_df, nBoot = 1000){
for(i in 1:nBoot){
lat <- rnorm(nrow(coord_df), mean = coord_df$lat, sd = coord_df$lat_se)
lat <- scale(lat)[,1]
fit <- lm(coord_df$day.yr ~ coord_df$cc*lat + coord_df$Fyear -1) #make sure attributes attached
if(i == 1){coefs = coef(fit)}else{coefs = rbind(coefs, coef(fit))}
}
fit_df <- data.frame(Estimate = apply(coefs, 2, mean),
LCI = apply(coefs, 2, function(x) quantile(x, 0.025)),
UCI = apply(coefs, 2, function(x) quantile(x, 0.975)))
return(fit_df)
}
woth_job_coord$Fyear<- factor(woth_job_coord$year, levels = c("2012","2013","2014"))
woth_mad_coord$Fyear<- factor(woth_mad_coord$year, levels = c("2012","2013","2014"))
LCC_boot<-iso_boot(coord_df = woth_job_coord)
LCC_boot
TCC_boot<-iso_boot(coord_df = woth_mad_coord)
TCC_boot
#####Condition
#Bootstrap function for latitude with estimated coefficients and 95% CI
class(woth_dd.ll$fat)
#
iso_boot <- function(coord_df, nBoot = 1000){
for(i in 1:nBoot){
lat <- rnorm(nrow(coord_df), mean = coord_df$lat, sd = coord_df$lat_se)
lat <- scale(lat)[,1]
fit <- lm(coord_df$Cond ~ coord_df$cc*lat + coord_df$Fsite + coord_df$Fyear -1) #make sure attributes attached
if(i == 1){coefs = coef(fit)}else{coefs = rbind(coefs, coef(fit))}
}
fit_df <- data.frame(Estimate = apply(coefs, 2, mean),
LCI = apply(coefs, 2, function(x) quantile(x, 0.025)),
UCI = apply(coefs, 2, function(x) quantile(x, 0.975)))
return(fit_df)
}
Cond_boot<-iso_boot(coord_df = woth_dd.ll)
Cond_boot
###at each site
iso_boot <- function(coord_df, nBoot = 1000){
for(i in 1:nBoot){
lat <- rnorm(nrow(coord_df), mean = coord_df$lat, sd = coord_df$lat_se)
lat <- scale(lat)[,1]
fit <- lm(coord_df$Cond ~ coord_df$cc*lat + coord_df$Fyear -1) #make sure attributes attached
if(i == 1){coefs = coef(fit)}else{coefs = rbind(coefs, coef(fit))}
}
fit_df <- data.frame(Estimate = apply(coefs, 2, mean),
LCI = apply(coefs, 2, function(x) quantile(x, 0.025)),
UCI = apply(coefs, 2, function(x) quantile(x, 0.975)))
return(fit_df)
}
woth_job_coord$Cond[woth_job_coord$fat=="0" | woth_job_coord$fat=="1"] <- "LEAN"
woth_job_coord$Cond[woth_job_coord$fat=="2" | woth_job_coord$fat=="3"| woth_job_coord$fat=="4"] <- "FAT"
table(woth_job_coord$Cond) #FAT=28, LEAN=67
woth_job_coord$Cond<-as.factor(woth_job_coord$Cond)
LCC_boot<-iso_boot(coord_df = woth_job_coord)
LCC_boot
woth_mad_coord$Cond[woth_mad_coord$fat=="0" | woth_mad_coord$fat=="1"] <- "LEAN"
woth_mad_coord$Cond[woth_mad_coord$fat=="2" | woth_mad_coord$fat=="3"| woth_mad_coord$fat=="4"] <- "FAT"
table(woth_mad_coord$Cond) #FAT=28, LEAN=67
woth_mad_coord$Cond<-as.factor(woth_mad_coord$Cond)
TCC_boot<-iso_boot(coord_df = woth_mad_coord)
TCC_boot
#############################################################################
#Compare among sites/ species
#three species moved through the sites at similar times
quantile(amre_dd.ll$day.yr)
quantile(oven_dd.ll$day.yr)
quantile(woth_dd.ll$day.yr)
amre_dd.ll$sex<-as.factor(amre_dd.ll$sex)
oven_dd.ll$sex<-as.factor(oven_dd.ll$sex)
woth_dd.ll$sex<-as.factor(woth_dd.ll$sex)
summary(amre_dd.ll$fat)
summary(oven_dd.ll$fat)
summary(woth_dd.ll$fat)
# oven_dd.ll<-oven_dd.ll[-c(21:23)]
# woth_dd.ll<-woth_dd.ll[-c(21:23)]
# amre_dd.ll<-amre_dd.ll[-c(21:23)]
names(amre_dd.ll)
names(oven_dd.ll)
names(woth_dd.ll)
oven_dd.ll$species<-c("oven")
woth_dd.ll$species<-c("woth")
amre_dd.ll$species<-c("amre")
amre_dd.ll$species<-as.factor(amre_dd.ll$species)
oven_dd.ll$species<-as.factor(oven_dd.ll$species)
woth_dd.ll$species<-as.factor(woth_dd.ll$species)
summary(amre_dd.ll)
summary(oven_dd.ll)
summary(woth_dd.ll)
all_dd.ll<-rbind(amre_dd.ll,oven_dd.ll, all=T)
all_dd.ll<-rbind(all_dd.ll,woth_dd.ll, all=T)
nrow(all_dd.ll) #184
summary(all_dd.ll)
mod2 <- with(all_dd.ll, lm(lat ~ 1))
mod1 <- with(all_dd.ll, lm(lat ~ Fyear-1)) #site
summary(mod1) # View model results
# Compare models using likelihood ratio test
anova(mod2, mod1)
#############################################################################
#Old stuff
#############################################################################
# #Do breeding latitudes pass through site at the same time?
# #convert date to day (amre_dd.ll$date)
# amre_dd.ll$doy <- strftime(amre_dd.ll$date, format = "%j")
# class(amre_dd.ll$doy) #92-133
# amre_dd.ll$doy<-as.numeric(amre_dd.ll$doy)
# plot(amre_dd.ll$doy,amre_dd.ll$dd)
############################################################
# Questions:
# Explore differences between sites in species numbers, age, sex, passage timing.
############################################################
#Compare sites for variables
table(amre_dd.ll$fat)
table(amre_dd.ll$site)
table(amre_dd.ll$year)
table(amre_dd.ll$age)
table(amre_dd.ll$sex)
table(amre_dd.ll$Cond)
table(amre_dd.ll$Fsite)
summary(amre_dd.ll)
head(amre_dd.ll)
table(amre_dd.ll$sex, amre_dd.ll$Fsite)
#Sites differ in Cond but not sex or age
table(amre_dd.ll$site,amre_dd.ll$Cond)
mytable <- table(amre_dd.ll$site,amre_dd.ll$Cond)
prop.table(mytable, 1)
table(amre_dd.ll$site,amre_dd.ll$sex)
mytable <- table(amre_dd.ll$site,amre_dd.ll$sex)
prop.table(mytable, 1)
table(amre_dd.ll$site,amre_dd.ll$age)
mytable <- table(amre_dd.ll$site,amre_dd.ll$age)
prop.table(mytable, 1)
table(amre_dd.ll$date,amre_dd.ll$doy)
# Plot the relationship between passage day and breeding latitude
ggplot(data = amre_dd.ll, aes(x = lat, y = day.yr)) + geom_point() + stat_smooth(method = "lm")
# Fit linear regression model
mod1 <- with(amre_dd.ll, lm(doy ~ lat))
summary(mod1)
mod2 <- with(amre_dd.ll, lm(doy ~ 1)) # Fit intercept-only model
# Compare models using likelihood ratio test
anova(mod2, mod1)
# Full model
full.mod <- with(amre_dd.ll, lm(lat ~ site*doy))
summary(full.mod)
#Is there a significant site effect of day of year?
doy.mod <- with(amre_dd.ll, lm(lat ~ site))
anova(site.mod, full.mod)
#plot by site
ggplot(data = amre_dd.ll, aes(x = lat, y = day.yr)) + geom_point() +
facet_wrap(~Fsite, nrow = 1) + stat_smooth(method = "lm")
#day of year by site
tiff(filename = "AMRE_doy_site_wght.tiff", width = 7, height = 5, units = "in", res = 300, compression = "lzw")
amre_doy <- ggplot(data = amre_dd.ll, aes(x = lat, y = day.yr)) +
geom_point(aes(color = Fsite), size=3, alpha = 0.5) +
labs(color = "Site")+
stat_smooth(method = "lm", aes(color = Fsite), size=3, se = FALSE) +
xlab("mean breeding latitude") + ylab("day of year")+
theme_bw()+ theme(text = element_text(size=18))+
theme(panel.grid.major =element_blank(),panel.grid.minor =element_blank())+
theme(legend.position = c(0.8, 0.2)) + theme(legend.key = element_rect(colour = NA))+
theme(legend.background = element_rect(fill="gray90"))
amre_doy #+ ggtitle("American Redstart breeding destinations\nfrom spring stopover sites")
#print to file
dev.off()
#does winter habitat, d13C, or condition influence timing, relative to destination?
# extract residuals from mod1 <- with(amre_dd.ll, lm(doy ~ y))
######################
#Age
# Fit linear regression model for day of year by age
mod1 <- with(amre_dd.ll, lm(doy ~ age*lat))
summary(mod1)
mod2 <- with(amre_dd.ll, lm(doy ~ age+lat)) # Fit intercept-only model
summary(mod2)
# Compare models using likelihood ratio test
anova(mod2, mod1)
#interaction term significant for latitude and age
###for each site
summary(arem_app_coord)
arem_app_coord2 <- arem_app_coord[which(arem_app_coord$age != 'AHY'),] #ASY=83, SY=30
arem_app_coord2$age<-as.factor(arem_app_coord2$age)
arem_mad_coord2 <- arem_mad_coord[which(arem_mad_coord$age != 'AHY'),] #ASY=83, SY=30
arem_mad_coord2$age<-as.factor(arem_mad_coord2$age)
arem_job_coord2 <- arem_job_coord[which(arem_job_coord$age != 'AHY'),] #ASY=83, SY=30
arem_job_coord2$age<-as.factor(arem_job_coord2$age)
mod3 <- with(arem_app_coord2, lm(day.yr ~ age+lat)) # Fit intercept-only model
summary(mod3)
mod4 <- with(arem_mad_coord2, lm(day.yr ~ age+lat)) # Fit intercept-only model
summary(mod4)
mod5 <- with(arem_job_coord2, lm(day.yr ~ age+lat)) # Fit intercept-only model
summary(mod5)
####################
#Sex
# Fit linear regression model for day of year by sex
mod1 <- with(amre_dd.ll, lm(doy ~ sex*lat))
summary(mod1)
mod2 <- with(amre_dd.ll, lm(doy ~ sex+lat)) # Fit intercept-only model
summary(mod2)
# Compare models using likelihood ratio test
anova(mod2, mod1)
#no significant interaction term significant
###for each site
summary(arem_app_coord)
arem_app_coord2$sex<-as.factor(arem_app_coord2$sex)
arem_mad_coord2$sex<-as.factor(arem_mad_coord2$sex)
arem_job_coord2$sex<-as.factor(arem_job_coord2$sex)
mod3 <- with(arem_app_coord2, lm(day.yr ~ sex+lat)) # Fit intercept-only model
summary(mod3)
mod4 <- with(arem_mad_coord2, lm(day.yr ~ sex+lat)) # Fit intercept-only model
summary(mod4)
mod5 <- with(arem_job_coord2, lm(day.yr ~ sex+lat)) # Fit intercept-only model
summary(mod5)
##################################################################################
#Do age and sexes heading to breeding latitudes pass through site at the same time?
#plot by age- same plot different colors
tiff(filename = "AMRE_age_wght.tiff", width = 7, height = 5, units = "in", res = 300, compression = "lzw")
amre_age <-ggplot(data = amre_dd.ll, aes(x = lat, y = doy)) +
geom_point(aes(color = age), size=3, alpha = 0.5) +
labs(color = "Age")+stat_smooth(method = "lm", aes(color = age), size=3, se = FALSE) +
xlab("mean breeding latitude") + ylab("day of year")+ theme_bw()+
theme(panel.grid.major =element_blank(),panel.grid.minor =element_blank())+
theme(text = element_text(size=18))+
theme(legend.position = c(0.8, 0.2)) + theme(legend.key = element_rect(colour = NA))+
theme(legend.background = element_rect(fill="gray90"))
amre_age #+ ggtitle("American Redstart breeding destinations\nfrom spring stopover sites")
#print to file
dev.off()
#plot by sex
tiff(filename = "AMRE_sex_wght.tiff", width = 7, height = 5, units = "in", res = 300, compression = "lzw")
amre_sex <- ggplot(data = amre_dd.ll, aes(x = lat, y = doy)) +
geom_point(aes(color = sex), size=3, alpha = 0.5) +
labs(color = "Sex")+ stat_smooth(method = "lm", aes(color = sex), size=3, se = FALSE) +
xlab("mean breeding latitude") + ylab("day of year")+ theme_bw()+
theme(panel.grid.major =element_blank(),panel.grid.minor =element_blank())+
theme(text = element_text(size=18))+
theme(legend.position = c(0.8, 0.2)) + theme(legend.key = element_rect(colour = NA))+
theme(legend.background = element_rect(fill="gray90"))
amre_sex #+ ggtitle("American Redstart breeding destinations\nfrom spring stopover sites")
#print to file
dev.off()
# Fit linear regression model
mod1 <- with(amre_dd.ll, lm(doy ~ lat*sex))
summary(mod1)
mod2 <- with(amre_dd.ll, lm(doy ~ lat+sex)) # Fit intercept-only model
summary(mod2)
# Compare models using likelihood ratio test
anova(mod2, mod1)
#interaction term not significant for latitude and sex
#Do lean and fat birds heading to the same breeding latitudes pass through site at the same time?
ggplot(data = amre_dd.ll, aes(x = lat, y = doy)) + geom_point(aes(color = Cond), size=3) +
labs(color = "Condition")+stat_smooth(method = "lm", aes(color = Cond), size=1.5) +
xlab("mean breeding latitude") + ylab("day of year")+ theme_bw()+
theme(text = element_text(size=18))+ theme(legend.position = c(0.8, 0.2))
# Fit linear regression model
summary(amre_dd.ll)
mod1 <- with(amre_dd.ll, lm(fat ~ doy*lat))
summary(mod1)
mod2 <- with(amre_dd.ll, lm(fat ~ doy+lat)) # Fit intercept-only model
summary(mod2)
# Compare models using likelihood ratio test
anova(mod2, mod1)
mod3 <- with(amre_dd.ll, lm(fat ~ doy)) # Fit intercept-only model
summary(mod3)
#interaction term not significant for latitude and condition
#no difference in timing for fat vs lean birds heading to the same latitude
#site effect of condition timing?
ggplot(data = amre_dd.ll, aes(x = y, y = doy)) + geom_point(aes(color = Cond)) +
stat_smooth(method = "lm", aes(color = Cond)) +
facet_wrap(~site, nrow = 1) + theme_bw()
#Sites differ in Cond:
table(amre_dd.ll$site,amre_dd.ll$Cond)
mytable <- table(amre_dd.ll$site,amre_dd.ll$Cond)
prop.table(mytable, 1)
#difference in condition among sites?
# Fit linear regression model
mod1 <- with(amre_dd.ll, lm(fat ~ Fsite))
summary(mod1)
mod2 <- with(amre_dd.ll, lm(fat ~ 1)) # Fit intercept-only model
# Compare models using likelihood ratio test
anova(mod2, mod1)
#remove APP for this one
amre_dd.ll2 <-amre_dd.ll[which(amre_dd.ll$site != 'APP'),]
nrow(amre_dd.ll2) #93
table(amre_dd.ll2$site, amre_dd.ll2$Cond)
mod2 <- with(amre_dd.ll2, lm(doy ~ y+Cond)) # Fit intercept-only model
summary(mod2)
head(amre_dd.ll2)
ggplot(data = amre_dd.ll2, aes(x = y, y = doy)) +
geom_point(aes(color = Cond), size=3) +
stat_smooth(method = "lm", aes(color = Cond), size=1.5) +
facet_wrap(~Fsite, nrow = 1) + xlab("mean breeding latitude") + ylab("day of year")+
theme_bw()+ theme(text = element_text(size=18))+ theme(legend.position = c(0.9, 0.2))+
theme(legend.background = element_rect(fill="gray90"))
#########################################################
##OVEN ASSIGN
#########################################################
dat$date <- as.Date(dat$date, format = "%Y-%m-%d")
oven_dd <- dat %>% filter(species == "OVEN")
## Subset OVEN data by site
oven_app_dd <- oven_dd %>% filter(site == "APP"& !is.na(dd))
oven_job_dd <- oven_dd %>% filter(site == "JOB"& !is.na(dd))
oven_mad_dd <- oven_dd %>% filter(site == "MAD"& !is.na(dd))
## Assign individuals from each site
oven_app_assign <- iso_assign(dd = oven_app_dd$dd, df_base = oven_base$df.ahy, lat = oven_base$y, lon = oven_base$x, names = oven_app_dd$band.no)
oven_job_assign <- iso_assign(dd = oven_job_dd$dd, df_base = oven_base$df.ahy, lat = oven_base$y, lon = oven_base$x, names = oven_job_dd$band.no)
oven_mad_assign <- iso_assign(dd = oven_mad_dd$dd, df_base = oven_base$df.ahy, lat = oven_base$y, lon = oven_base$x, names = oven_mad_dd$band.no)
#add weighteing by abundnace
oven_app_assign <- abun_assign(iso_data = oven_app_assign, rel_abun = oven_base$rel.abun, iso_weight = -0.7, abun_weight = 0)
oven_job_assign <- abun_assign(iso_data = oven_job_assign, rel_abun = oven_base$rel.abun, iso_weight = -0.7, abun_weight = 0)
oven_mad_assign <- abun_assign(iso_data = oven_mad_assign, rel_abun = oven_base$rel.abun, iso_weight = -0.7, abun_weight = 0)
## Create dataframe with assignment results
##convert to a matrix to rearange
oven_app_mat <- matrix(oven_app_assign$wght_origin, nrow = nrow(oven_base), ncol = length(oven_app_dd$dd), byrow = FALSE)
oven_job_mat <- matrix(oven_job_assign$wght_origin, nrow = nrow(oven_base), ncol = length(oven_job_dd$dd), byrow = FALSE)
oven_mad_mat <- matrix(oven_mad_assign$wght_origin, nrow = nrow(oven_base), ncol = length(oven_mad_dd$dd), byrow = FALSE)
oven_assign <- data.frame(Latitude = oven_base$y,
Longitude = oven_base$x,
app_origin = apply(oven_app_mat, 1, sum)/ncol(oven_app_mat),
job_origin = apply(oven_job_mat, 1, sum)/ncol(oven_job_mat),
mad_origin = apply(oven_mad_mat, 1, sum)/ncol(oven_mad_mat))
##plot assignment from each site
## Write results to ~Results
write.csv(oven_assign, file = "Results/oven_assign.csv", row.names = FALSE)
##Use to measure mean lat long/ site, without error
#loop through individuals from a site, in columns
#app
oven_app_coord <- iso.assign2::wght_coord(summ = oven_app_assign, iso = FALSE) %>% rename(band.no = indv) %>%
left_join(., oven_app_dd)
with(oven_app_coord, summary(lm(lat ~ day.yr)))
#job
oven_job_coord <- iso.assign2::wght_coord(summ = oven_job_assign, iso = FALSE) %>% rename(band.no = indv) %>%
left_join(., oven_job_dd)
with(oven_job_coord, summary(lm(lat ~ day.yr)))
#mad
oven_mad_coord <- iso.assign2::wght_coord(summ = oven_mad_assign, iso = FALSE) %>% rename(band.no = indv) %>%
left_join(., oven_mad_dd)
with(oven_mad_coord, summary(lm(lat ~ day.yr)))
#Merge file with attributes and mean lat long for all OVEN
oven_dd.ll<-rbind(oven_app_coord,oven_job_coord)
oven_dd.ll<-rbind(oven_dd.ll,oven_mad_coord)
nrow(oven_dd.ll) #150
summary(oven_dd.ll)
#Does breeding destination (latitude) differ for site?
mod2 <- with(oven_dd.ll, lm(lat ~ 1))
mod1 <- with(oven_dd.ll, lm(lat ~ Fsite)) #site
summary(mod1) # View model results
# Compare models using likelihood ratio test
anova(mod2, mod1)
#There are differences in latitude between
#Categorize fat 0/1 as lean, 2-4 as fat
table(oven_dd.ll$fat)
oven_dd.ll$Cond[oven_dd.ll$fat=="0" | oven_dd.ll$fat=="1"] <- "LEAN"
oven_dd.ll$Cond[oven_dd.ll$fat=="2" | oven_dd.ll$fat=="3"| oven_dd.ll$fat=="4"] <- "FAT"
table(oven_dd.ll$Cond) #FAT=28, LEAN=67
oven_dd.ll$Cond<-as.factor(oven_dd.ll$Cond)
#change order of levels for sites
oven_dd.ll$Fsite<- factor(oven_dd.ll$site, levels = c("MAD","JOB","APP"), labels=c("Texas","Louisiana","Florida"))
table(oven_dd.ll$fat)
table(oven_dd.ll$site)
table(oven_dd.ll$year)
table(oven_dd.ll$age)
table(oven_dd.ll$Cond)
table(oven_dd.ll$Fsite)
summary(amre_dd.ll)
#Do breeding latitudes pass through site at the same time?
#convert date to day
oven_dd.ll$doy <- strftime(oven_dd.ll$date, format = "%j")
class(oven_dd.ll$doy) #92-133
oven_dd.ll$doy<-as.numeric(oven_dd.ll$doy)
plot(oven_dd.ll$doy,oven_dd.ll$dd)
table(oven_dd.ll$date,oven_dd.ll$doy)
#Is there a day of year effect?
full.mod <- with(oven_dd.ll, lm(lat ~ Fsite+doy))
site.mod <- with(oven_dd.ll, lm(lat ~ Fsite))
anova(site.mod, full.mod)
summary(full.mod)
#plot by site
ggplot(data = oven_dd.ll, aes(x = lat, y = doy)) + geom_point() +
facet_wrap(~site, nrow = 1) + stat_smooth(method = "lm")
#Does breeding destination (latitude) differ for site?
mod2 <- with(oven_dd.ll, lm(lat ~ 1))
mod1 <- with(oven_dd.ll, lm(lat ~ Fsite))
summary(mod1) # View model results
# Compare models using likelihood ratio test
anova(mod2, mod1)
#There are differences in latitude between
#day of year by site
tiff(filename = "OVEN_doy_site.tiff", width = 7, height = 5, units = "in", res = 300, compression = "lzw")
oven_doy <- ggplot(data = oven_dd.ll, aes(x = lat, y = doy)) +
geom_point(aes(color = Fsite), size=3, alpha = 0.5) +
labs(color = "Site")+
stat_smooth(method = "lm", aes(color = Fsite), size=3, se = FALSE) +
xlab("mean breeding latitude") + ylab("day of year")+
theme_bw()+ theme(text = element_text(size=18))+
theme(panel.grid.major =element_blank(),panel.grid.minor =element_blank())+
theme(legend.position = c(0.8, 0.2)) + theme(legend.key = element_rect(colour = NA))+
theme(legend.background = element_rect(fill="gray90"))
amre_doy #+ ggtitle("American Redstart breeding destinations\nfrom spring stopover sites")
#print to file
dev.off()
###################### Age
# Fit linear regression model for day of year by age
oven_dd.ll2 <- oven_dd.ll[which(oven_dd.ll$age != 'AHY'),]
nrow(oven_dd.ll2)
table(oven_dd.ll2$site, oven_dd.ll2$age)
table(oven_dd.ll2$age)
oven_dd.ll2$age<-as.factor(oven_dd.ll2$age)
mod1 <- with(oven_dd.ll2, lm(doy ~ age*lat))
summary(mod1)
mod2 <- with(oven_dd.ll2, lm(doy ~ age+lat)) # Fit intercept-only model
summary(mod2)
# Compare models using likelihood ratio test
anova(mod2, mod1)
mod3 <- with(oven_dd.ll2, lm(doy ~ age)) # Fit intercept-only model
summary(mod3)
#interaction term not significant for latitude and age
###for each site
summary(oven_app_coord)
oven_app_coord2 <- oven_app_coord[which(oven_app_coord$age != 'AHY'),] #ASY=83, SY=30
oven_app_coord2$age<-as.factor(oven_app_coord2$age)
oven_mad_coord2 <- oven_mad_coord[which(oven_mad_coord$age != 'AHY'),] #ASY=83, SY=30
oven_mad_coord2$age<-as.factor(oven_mad_coord2$age)
oven_job_coord2 <- oven_job_coord[which(oven_job_coord$age != 'AHY'),] #ASY=83, SY=30
oven_job_coord2$age<-as.factor(oven_job_coord2$age)
mod6 <- with(oven_app_coord2, lm(day.yr ~ age))
summary(mod6)
mod4 <- with(oven_mad_coord2, lm(day.yr ~ age))
summary(mod4)
mod5 <- with(oven_job_coord2, lm(day.yr ~ age))
summary(mod5)
#Do age heading to breeding latitudes pass through site at the same time?
#plot by age- same plot different colors
tiff(filename = "OVEN_age.tiff", width = 7, height = 5, units = "in", res = 300, compression = "lzw")
oven_age <-ggplot(data = oven_dd.ll2, aes(x = lat, y = doy)) +
geom_point(aes(color = age), size=3, alpha = 0.5) +
labs(color = "Age")+stat_smooth(method = "lm", aes(color = age), size=3, se = FALSE) +
xlab("mean breeding latitude") + ylab("day of year")+ theme_bw()+
theme(panel.grid.major =element_blank(),panel.grid.minor =element_blank())+
theme(text = element_text(size=18))+
theme(legend.position = c(0.8, 0.2)) + theme(legend.key = element_rect(colour = NA))+
theme(legend.background = element_rect(fill="gray90"))
oven_age
dev.off()
##################
#Condition
#Do lean and fat birds heading to the same breeding latitudes pass through site at the same time?
ggplot(data = oven_dd.ll, aes(x = lat, y = doy)) + geom_point(aes(color = Cond), size=3) +
labs(color = "Condition")+stat_smooth(method = "lm", aes(color = Cond), size=1.5) +
xlab("mean breeding latitude") + ylab("day of year")+ theme_bw()+
theme(text = element_text(size=18))+ theme(legend.position = c(0.8, 0.2))
# Fit linear regression model
mod1 <- with(oven_dd.ll, lm(fat ~ doy*lat))
summary(mod1)
mod2 <- with(oven_dd.ll, lm(fat ~ doy+lat)) # Fit intercept-only model
summary(mod2)
# Compare models using likelihood ratio test
anova(mod2, mod1)
mod3 <- with(oven_dd.ll, lm(fat ~ doy)) # Fit intercept-only model
summary(mod3)
#interaction term not significant for latitude and condition
#no difference in timing for fat vs lean birds heading to the same latitude
#site effect of condition timing?
ggplot(data = oven_dd.ll, aes(x = lat, y = doy)) + geom_point(aes(color = Cond)) +
stat_smooth(method = "lm", aes(color = Cond)) +
facet_wrap(~site, nrow = 1) + theme_bw()
#Sites differ in Cond:
table(oven_dd.ll$site,oven_dd.ll$Cond)
mytable <- table(oven_dd.ll$site,oven_dd.ll$Cond)
prop.table(mytable, 1)
#difference in condition among sites?
# Fit linear regression model
mod1 <- with(oven_dd.ll, lm(fat ~ Fsite))
summary(mod1)
mod2 <- with(oven_dd.ll, lm(fat ~ 1)) # Fit intercept-only model
# Compare models using likelihood ratio test
anova(mod2, mod1)
########################################################
##WOTH ASSIGN
########################################################
woth_dd <- dat %>% filter(species == "WOTH")
## Subset WOTH data by site
woth_app_dd <- woth_dd %>% filter(site == "APP"& !is.na(dd))
woth_job_dd <- woth_dd %>% filter(site == "JOB"& !is.na(dd))
woth_mad_dd <- woth_dd %>% filter(site == "MAD"& !is.na(dd))
## Assign individuals from each site
woth_app_assign <- iso_assign(dd = woth_app_dd$dd, df_base = woth_base$df.ahy, lat = woth_base$y, lon = woth_base$x, names = woth_app_dd$band.no)
woth_job_assign <- iso_assign(dd = woth_job_dd$dd, df_base = woth_base$df.ahy, lat = woth_base$y, lon = woth_base$x, names = woth_job_dd$band.no)
woth_mad_assign <- iso_assign(dd = woth_mad_dd$dd, df_base = woth_base$df.ahy, lat = woth_base$y, lon = woth_base$x, names = woth_mad_dd$band.no)
#add weighteing by abundnace
woth_app_assign <- abun_assign(iso_data = woth_app_assign, rel_abun = woth_base$rel.abun, iso_weight = -0.7, abun_weight = 0)
woth_job_assign <- abun_assign(iso_data = woth_job_assign, rel_abun = woth_base$rel.abun, iso_weight = -0.7, abun_weight = 0)
woth_mad_assign <- abun_assign(iso_data = woth_mad_assign, rel_abun = woth_base$rel.abun, iso_weight = -0.7, abun_weight = 0)
## Create dataframe with assignment results
##convert to a matrix to rearange
woth_app_mat <- matrix(woth_app_assign$wght_origin, nrow = nrow(woth_base), ncol = length(woth_app_dd$dd), byrow = FALSE)
woth_job_mat <- matrix(woth_job_assign$wght_origin, nrow = nrow(woth_base), ncol = length(woth_job_dd$dd), byrow = FALSE)
woth_mad_mat <- matrix(woth_mad_assign$wght_origin, nrow = nrow(woth_base), ncol = length(woth_mad_dd$dd), byrow = FALSE)
woth_assign <- data.frame(Latitude = woth_base$y,
Longitude = woth_base$x,
app_origin = apply(woth_app_mat, 1, sum)/ncol(woth_app_mat),
job_origin = apply(woth_job_mat, 1, sum)/ncol(woth_job_mat),
mad_origin = apply(woth_mad_mat, 1, sum)/ncol(woth_mad_mat))
## Write results to ~Results
write.csv(woth_assign, file = "Results/woth_assign.csv", row.names = FALSE)
#loop through individuals from a site, in columns
#app
woth_app_coord <- iso.assign2::wght_coord(summ = woth_app_assign, iso = FALSE) %>% rename(band.no = indv) %>%
left_join(., woth_app_dd)
with(woth_app_coord, summary(lm(lat ~ day.yr)))
#job
woth_job_coord <- iso.assign2::wght_coord(summ = woth_job_assign, iso = FALSE) %>% rename(band.no = indv) %>%
left_join(., woth_job_dd)
with(woth_job_coord, summary(lm(lat ~ day.yr)))
#mad
woth_mad_coord <- iso.assign2::wght_coord(summ = woth_mad_assign, iso = FALSE) %>% rename(band.no = indv) %>%
left_join(., woth_mad_dd)
with(woth_mad_coord, summary(lm(lat ~ day.yr)))
#Merge file with attributes and mean lat long for all OVEN
woth_dd.ll<-rbind(woth_app_coord,woth_job_coord)
woth_dd.ll<-rbind(woth_dd.ll,woth_mad_coord)
nrow(woth_dd.ll) #184
summary(woth_dd.ll)
#Categorize fat 0/1 as lean, 2-4 as fat
table(woth_dd.ll$fat)
woth_dd.ll$Cond[woth_dd.ll$fat=="0" | woth_dd.ll$fat=="1"] <- "LEAN"
woth_dd.ll$Cond[woth_dd.ll$fat=="2" | woth_dd.ll$fat=="3"| woth_dd.ll$fat=="4"] <- "FAT"
table(woth_dd.ll$Cond) #FAT=28, LEAN=67
woth_dd.ll$Cond<-as.factor(woth_dd.ll$Cond)
#change order of levels for sites
woth_dd.ll$Fsite<- factor(woth_dd.ll$site, levels = c("MAD","JOB","APP"), labels=c("Texas","Louisiana","Florida"))
table(woth_dd.ll$fat)
table(woth_dd.ll$site)
table(woth_dd.ll$year)
table(woth_dd.ll$age)
table(woth_dd.ll$sex)
table(woth_dd.ll$Cond)
table(woth_dd.ll$Fsite)
summary(woth_dd.ll)
#Does breeding destination (latitude) differ for site?
mod2 <- with(woth_dd.ll, lm(lat ~ 1))
mod1 <- with(woth_dd.ll, lm(lat ~ site))
summary(mod1) # View model results
# Compare models using likelihood ratio test
anova(mod2, mod1)
#There are differences in latitude between
#Do breeding latitudes pass through site at the same time?
#convert date to day
woth_dd.ll$doy <- strftime(woth_dd.ll$date, format = "%j")
class(woth_dd.ll$doy) #92-133
woth_dd.ll$doy<-as.numeric(woth_dd.ll$doy)
plot(woth_dd.ll$doy,woth_dd.ll$dd)
#Does lat vary by doy?
doy.mod <- with(woth_dd.ll, lm(lat ~ doy))
no.mod <- with(woth_dd.ll, lm(lat ~ 1))
anova(no.mod, doy.mod)
#Yes, doy matters
summary(doy.mod)
#Is there an interaction between site and doy?
full.mod <- with(woth_dd.ll, lm(lat ~ Fsite*doy))
site.mod <- with(woth_dd.ll, lm(lat ~ Fsite+doy))
anova(site.mod, full.mod)
#Yes, interaction significant so doy for some sites
head(woth_app_coord)
mod6 <- with(woth_app_coord, lm(lat ~ day.yr))
summary(mod6)
mod4 <- with(woth_mad_coord, lm(lat ~ day.yr))
summary(mod4)
mod5 <- with(woth_job_coord, lm(lat ~ day.yr))
summary(mod5)
#plot by site
ggplot(data = woth_dd.ll, aes(x = lat, y = doy)) + geom_point() +
facet_wrap(~site, nrow = 1) + stat_smooth(method = "lm")
#day of year by site
tiff(filename = "WOTH_doy_site.tiff", width = 7, height = 5, units = "in", res = 300, compression = "lzw")
woth_doy <- ggplot(data = woth_dd.ll, aes(x = lat, y = doy)) +
geom_point(aes(color = Fsite), size=3, alpha = 0.5) +
labs(color = "Site")+
stat_smooth(method = "lm", aes(color = Fsite), size=3, se = FALSE) +
xlab("mean breeding latitude") + ylab("day of year")+
theme_bw()+ theme(text = element_text(size=18))+
theme(panel.grid.major =element_blank(),panel.grid.minor =element_blank())+
theme(legend.position = c(0.8, 0.2)) + theme(legend.key = element_rect(colour = NA))+
theme(legend.background = element_rect(fill="gray90"))
woth_doy
dev.off()
################age
woth_dd.ll2 <- woth_dd.ll[which(woth_dd.ll$age != 'AHY'),]
nrow(woth_dd.ll2)
table(woth_dd.ll2$site, woth_dd.ll2$age)
table(woth_dd.ll2$age)
woth_dd.ll3 <- woth_dd.ll2[which(woth_dd.ll2$site != 'APP'),]
table(woth_dd.ll3$site, woth_dd.ll3$age)
nrow(woth_dd.ll3)
woth_dd.ll3$age<-as.factor(woth_dd.ll3$age)
#Do age heading to breeding latitudes pass through site at the same time?
#plot by age- same plot different colors
tiff(filename = "WOTH_age.tiff", width = 7, height = 5, units = "in", res = 300, compression = "lzw")
woth_age <-ggplot(data = woth_dd.ll3, aes(x = lat, y = doy)) +
geom_point(aes(color = age), size=3, alpha = 0.5) +
labs(color = "Age")+stat_smooth(method = "lm", aes(color = age), size=3, se = FALSE) +
xlab("mean breeding latitude") + ylab("day of year")+ theme_bw()+
theme(panel.grid.major =element_blank(),panel.grid.minor =element_blank())+
theme(text = element_text(size=18))+
theme(legend.position = c(0.8, 0.2)) + theme(legend.key = element_rect(colour = NA))+
theme(legend.background = element_rect(fill="gray90"))
woth_age
dev.off()
woth_age <-ggplot(data = woth_dd.ll3, aes(x = lat, y = doy)) +
geom_point(aes(color = age), size=3, alpha = 0.5) +
labs(color = "Age")+stat_smooth(method = "lm", aes(color = age), size=3, se = FALSE) +
xlab("mean breeding latitude") + ylab("day of year")+ theme_bw()+
facet_wrap(~Fsite, nrow = 1) +
theme(panel.grid.major =element_blank(),panel.grid.minor =element_blank())+
theme(text = element_text(size=18))+
theme(legend.position = c(0.9, 0.2)) + theme(legend.key = element_rect(colour = NA))+
theme(legend.background = element_rect(fill="gray90"))
woth_age
############################################################
### Measure model performance using known-origin birds -----
############################################################
# ### AMRE
# amre_ko <- read.csv("Raw data/AMRE_dd.csv")
#
# ## Isotope assignment
# amre_assign <- iso_assign(dd = amre_ko$dD, df_base = amre_base$df.ahy, lat = amre_base$y, lon= amre_base$x)
# #optional arguments= can give indiv a unique ID, can change the odd ratio to any value 0-1, right now is 67%
#
# #Weighted abundance
# amre_base$rel.abun <- amre_base$abun / sum(amre_base$abun)
# amre_assign2 <- abun_assign(iso_data = amre_assign, rel_abun = amre_base$rel.abun, iso_weight = 0, abun_weight = -1)
# #adds abunance assignment results to isotope results; weights from Rushing & Studds (in revision)
# #for WOTH & OVEN: iso_weight = -0.7, abun_weight = 0
#
# ## Weighted coordinates
# amre_coord <- iso.assign2::wght_coord(summ = amre_assign2, iso = FALSE)
# # if iso = TRUE, coordinates estimated using isotope-only assignment; if iso = FALSe, estimated from abundance model
# #should compare results
#
# ## Add auxillary variables to weighted coords
# ## ignore warning message for too many values
# amre_ko$indv <- paste("Indv_", seq(1: nrow(amre_ko)), sep = "")
#
# amre_coord <- amre_coord %>% left_join(., amre_ko, by = "indv") %>%
# rename(lat_true = lat.y, lon_true = lon.y, lat = lat.x, lon = lon.x) %>%
# mutate(lat_correct = ifelse(lat_true > lat_LCI & lat_true < lat_UCI, 1, 0),
# lat_error = lat_true - lat) %>%
# separate(SITE, c("site", "state"), sep = ",") %>%
# select(indv, lon, lat, lon_LCI, lat_LCI, lon_UCI, lat_UCI, ID, site, state, lat_true, lat_correct, lat_error)
# #ignore Warning messages:1: Too many value
#
# ####Need to remove "Central" and "no name"
# nrow(amre_coord)
# #list(amre_coord$state)
# #amre_coord[is.na(amre_coord$state),] #all na are NY
# #5 with state missing, all in NY, Albany Pine Bush Preserve (2), Karner Barrens West (2),
# #KMLS Road Barrens
# #amre_coord$state[is.na(amre_coord$state)]
# amre_coord$state[which(is.na(amre_coord$state))]<- c(" NY")
# names(amre_coord)
# #remove "central" interestingly, all states have a space in front of name
# amre_coord<-amre_coord[which(amre_coord$state != ' Central'),]
# names(amre_coord)
# nrow(amre_coord)
#
# ## Test 1: Proportion of individuals w/ true lat w/i coord 95% CI
# amre_coord %>% group_by(state) %>%
# summarize(correct = sum(lat_correct), n = length(lat_correct), prob = correct/n, lat = max(lat_true)) %>%
# ggplot(., aes(x = lat, y = prob, label=state)) + geom_point()+ geom_text(vjust=1.5)
#
# amre_coord %>%
# ggplot(., aes(x = lat_true, y = lat)) + geom_point() +
# geom_abline(intercept = 0, slope = 1, linetype = 'longdash', alpha = 0.5)
#
# table(amre_coord$state)
# #GA LA MD ME MI MO NC NY VA VT WV
# #10 26 31 10 25 32 39 5 7 22 5
#
# ############################################################
# ### Measure model performance using known-origin birds -----
# ############################################################
# ### OVEN
# load("Raw data/OVEN_data.RData") #OVEN_dd object will be loaded
# head(oven_dd)
#
# ## Isotope assignment
# oven_assign <- iso_assign(dd = oven_dd$dD, df_base = oven_base$df.ahy, lat = oven_base$y, lon= oven_base$x)
#
# #Weighted abundance
# oven_base$rel.abun <- oven_base$abun / sum(oven_base$abun)
# oven_assign2 <- abun_assign(iso_data = oven_assign, rel_abun = oven_base$rel.abun, iso_weight = -0.7, abun_weight = 0)
# #adds abunance assignment results to isotope results; weights from Rushing & Studds (in revision)
# #for WOTH & OVEN: iso_weight = -0.7, abun_weight = 0
#
# ## Weighted coordinates
# oven_coord <- iso.assign2::wght_coord(summ = oven_assign2, iso = FALSE)
# # if iso = TRUE, coordinates estimated using isotope-only assignment; if iso = FALSe, estimated from abundance model
#
# ## Add auxillary variables to weighted coords
# ## ignore warning message for too many values
# head(oven_dd)
# oven_dd$indv <- paste("Indv_", seq(1: nrow(oven_dd)), sep = "")
# oven_coord <- oven_coord %>% left_join(., oven_dd, by = "indv") %>%
# rename(lat_true = lat.y, lon_true = lon.y, lat = lat.x, lon = lon.x) %>%
# mutate(lat_correct = ifelse(lat_true > lat_LCI & lat_true < lat_UCI, 1, 0),
# lat_error = lat_true - lat) %>%
# separate(SITE, c("site", "state"), sep = ",") %>%
# select(indv, lon, lat, lon_LCI, lat_LCI, lon_UCI, lat_UCI, ID, site, state, lat_true, lat_correct, lat_error)
#
# nrow(oven_coord)
# table(oven_coord$state)
#
# ## Test 1: Proportion of individuals w/ true lat w/i coord 95% CI
# oven_coord %>% group_by(state) %>%
# summarize(correct = sum(lat_correct), n = length(lat_correct), prob = correct/n, lat = max(lat_true)) %>%
# ggplot(., aes(x = lat, y = prob, label=state)) + geom_point()+ geom_text(vjust=1.5)
#
# oven_coord %>%
# ggplot(., aes(x = lat_true, y = lat)) + geom_point() +
# geom_abline(intercept = 0, slope = 1, linetype = 'longdash', alpha = 0.5)
#
# table(oven_coord$state)
# #MD MI MO NC VT WV
# #5 5 5 5 5 5
#
# ############################################################
# ### Measure model performance using known-origin birds -----
# ############################################################
# ### WOTH
# load("Raw data/WOTH_data.RData") #OVEN_dd object will be loaded
# head (woth_dd)
# #add lat long to file
# # NC: 35.41, 83.12
# # VA: 38.71, 77.15
# # IN: 38.84, 86.82
# # MI: 42.16, 85.47
# # VT: 44.51, 73.15
# table(woth_dd$state)
# woth_dd$state<-toupper(woth_dd$state)
# woth_dd$lat<- 35.4
# woth_dd$lon<- 83.12
# woth_dd$lat[which(woth_dd$state == "VA")] <- 38.71
# woth_dd$lon[which(woth_dd$state == "VA")] <- 77.15
# woth_dd$lat[which(woth_dd$state == "IN")] <- 38.84
# woth_dd$lon[which(woth_dd$state == "IN")] <- 86.82
# woth_dd$lat[which(woth_dd$state == "MI")] <- 42.16
# woth_dd$lon[which(woth_dd$state == "MI")] <- 85.47
# woth_dd$lat[which(woth_dd$state == "VT")] <- 44.51
# woth_dd$lon[which(woth_dd$state == "VT")] <- 73.15
# table(woth_dd$lat,woth_dd$state)
# table(woth_dd$lon,woth_dd$state)
#
# ## Isotope assignment
# woth_assign <- iso_assign(dd = woth_dd$dd, df_base = woth_base$df.ahy, lat = woth_base$y, lon= woth_base$x)
#
# ## Weighted abundance
# woth_base$rel.abun <- woth_base$abun / sum(woth_base$abun)
# woth_assign2 <- abun_assign(iso_data = woth_assign, rel_abun = woth_base$rel.abun, iso_weight = -0.7, abun_weight = 0)
#
# ## Weighted coordinates
# woth_coord <- iso.assign2::wght_coord(summ = woth_assign2, iso = FALSE)
#
# ## Add auxillary variables to weighted coords
# ## ignore warning message for too many values
# woth_dd$indv <- paste("Indv_", seq(1: nrow(woth_dd)), sep = "")
# head(woth_dd)
# head(woth_coord)
# woth_coord <- woth_coord %>% left_join(., woth_dd, by = "indv") %>%
# rename(lat_true = lat.y, lon_true = lon.y, lat = lat.x, lon = lon.x) %>%
# mutate(lat_correct = ifelse(lat_true > lat_LCI & lat_true < lat_UCI, 1, 0), lat_error = lat_true - lat) %>%
# select(indv, lon, lat, lon_LCI, lat_LCI, lon_UCI, lat_UCI, state, lat_true, lat_correct, lat_error)
#
# ## Test 1: Proportion of individuals w/ true lat w/i coord 95% CI
# woth_coord %>% group_by(state) %>%
# summarize(correct = sum(lat_correct), n = length(lat_correct), prob = correct/n, lat = max(lat_true)) %>%
# ggplot(., aes(x = lat, y = prob, label=state)) + geom_point()+ geom_text(vjust=1.5)
#
# woth_coord %>%
# ggplot(., aes(x = lat_true, y = lat)) + geom_point() +
# geom_abline(intercept = 0, slope = 1, linetype = 'longdash', alpha = 0.5)
#
# ## All three species: Proportion of individuals w/ true lat w/i coord 95% CI
# ##summary
# amre_state<-amre_coord %>% group_by(state) %>% summarize(correct = sum(lat_correct), n = length(lat_correct), prob = correct/n, lat = max(lat_true))
# oven_state<-oven_coord %>% group_by(state) %>% summarize(correct = sum(lat_correct), n = length(lat_correct), prob = correct/n, lat = max(lat_true))
# woth_state<-woth_coord %>% group_by(state) %>% summarize(correct = sum(lat_correct), n = length(lat_correct), prob = correct/n, lat = max(lat_true))
# head(amre_state)
# head(oven_state)
# head(woth_state)
# #add species name
# woth_state$species<- "WOTH"
# oven_state$species<- "OVEN"
# amre_state$species<- "AMRE"
# #combine
# all_coord<-rbind(woth_state, oven_state)
# all_coord2<-rbind(all_coord, amre_state)
# head(all_coord2)
# #plot
# ggplot(all_coord2, aes(x = lat, y = prob, label=state, group=species)) + geom_point(aes(colour = species)) +
# geom_text(vjust=1.5) # + geom_line(y=0.75) + geom_line(y=0.5) + geom_line(y=0.25)
|
2f681c31247cf16c187c3d4dd2b281e10355295f | b151e3598ccb33656c1617f6152de34eac332fd2 | /testdata.R | 4067412180f27bb58a383e347a2c952f8bd724f0 | [] | no_license | ssimpore/testing | d4389c9f1c73e5d1489554be3ca8baeb2037fca8 | 754b0ff818d9db6be14040e00ebfaf387c1aba3f | refs/heads/master | 2022-10-23T05:25:08.818194 | 2020-06-20T21:24:31 | 2020-06-20T21:24:31 | 273,335,433 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 158 | r | testdata.R |
df = read.csv("C:/Users/JG6010/Dropbox/DOCUMENT/Formation/Data Science/JOHNS HOPKINS UNIVERSITY/The Data Scientist Toolbox/R/TestR/Data/Prod.CSV")
View(df) |
3919ede66112fbc2bde0db34e53a663601c99944 | 10f047c7631b3aad90c7410c567c588993bfa647 | /DispersalSimulation/Thesis/ModelGraphs.R | 3ded325e3d04d2084425ee718bc6ec755a0229dd | [] | no_license | ruthubc/ruthubc | ee5bc4aa2b3509986e8471f049b320e1b93ce1d5 | efa8a29fcff863a2419319b3d156b293a398c3a9 | refs/heads/master | 2021-01-24T08:05:40.590243 | 2017-08-30T01:37:56 | 2017-08-30T01:37:56 | 34,295,740 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 6,895 | r | ModelGraphs.R | # TODO: Add comment
#
# Author: Ruth
###############################################################################
setwd("C:/Users/Ruth/Dropbox/")
library(FlexParamCurve)
library(nlshelper)
mytheme <- theme_bw(base_size=15) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
panel.border = element_rect(fill = NA, colour = "black", linetype=1, size = 0.5),
legend.background = element_rect(fill="white", size=0.5, linetype="solid", colour ="black"), legend.text=element_text(size=8),
strip.background = element_rect(fill="white", size=0.7, linetype="solid", colour ="black"))
importDispFile$log_metPopAgeMax <- importDispFile$metPopAgeMax
# constant variables
env1<- 0.0
no_off <- 6
subDispFile <- subset(importDispFile, Comp_meas != 0.5)
subDispFile <- subset(subDispFile, max_no_off == no_off & input_var == env1)
aveFile <- ddply(subDispFile, .(ad_dsp_fd, Comp_meas), summarize,
metPopAgeMax = mean(metPopAgeMax))
png("RuthSync/Thesis/Presentation/3_compdispNoEnv.png", width = 1550, height = 950, units = "px", res = 200)
'''
ggplot(aveFile, aes(x = as.factor(Comp_meas), y = as.factor(ad_dsp_fd), fill = (metPopAgeMax))) +
geom_tile(colour = "gray50", size=0.5) +
mytheme + xlab("Degree of contest competition") + ylab("Minimum dispersal size") +
scale_fill_gradient(trans = "log", low="lightcyan", high="navyblue",
name = "Metapopulation\nsurvival (generations)", breaks = c(5, 10, 30, 100, 500))
'''
ggplot(aveFile, aes(x = as.factor(Comp_meas), y = as.factor(ad_dsp_fd), fill = (metPopAgeMax))) +
geom_tile(colour = "gray50", size=0.5) +
mytheme + xlab("Degree of contest competition") + ylab("Minimum dispersal size") +
scale_fill_gradient(low="white", high="grey2", guide = FALSE, breaks = c(5, 10, 30, 100, 500))
dev.off()
# with environmental variation
no_off <- 6
subDispFile <- subset(importDispFile, Comp_meas != 0.5)
subDispFile_noise <- subset(subDispFile, max_no_off == no_off & input_var > 0.6)
aveFile_noise <- ddply(subDispFile_noise, .(ad_dsp_fd, Comp_meas), summarize,
metPopAgeMax = mean(metPopAgeMax))
png("RuthSync/Thesis/Presentation/3_compdispWithNoise.png", width = 1550, height = 950, units = "px", res = 200)
ggplot(aveFile_noise, aes(x = as.factor(Comp_meas), y = as.factor(ad_dsp_fd), fill = (metPopAgeMax))) +
geom_tile(colour = "gray50", size=0.5) +
mytheme + xlab("Degree of contest competition") + ylab("Minimum dispersal size") +
scale_fill_gradient(trans = "log", low="lightcyan", high="navyblue",
name = "Metapopulation\nsurvival", breaks = c(5, 10, 30, 100, 500)) +
theme(legend.position="bottom")
dev.off()
########### With environmental variation #################################
Label_compLegend <- "degree of\ncontest\ncompetition"
Label_compAxis <- "degree of contest competition"
Label_dspSizeLegend <- "minimum\nindividual\ndispersal size"
Label_dspSizeAxis <- "minimum individual dispersal size"
Label_Met <- "metapopulation survival time"
Label_pop <- "population survival time"
set_ad_dsp_fd1 <- 0.8
set_ad_dsp_fd2 <- 0.6
subDispFile <- subset(importDispFile, max_no_off == no_off)
subDispFile <- subset(subDispFile, Comp_meas != 0.5 & input_var != 0.05 & input_var != 0.15)
subDispFile$nls_crv <- NULL
nrow(subDispFile)
sub_adDsp1.2 <- subset(subDispFile, ad_dsp_fd == 1.2)
png("RuthSync/Thesis/Presentation/3_compdispNoEnv_adDsp1pt2.png", width = 1750, height = 600, units = "px", res = 200)
ggplot(sub_adDsp1.2 , aes(x = input_var, y = (metPopAgeMax), color = as.factor(Comp_meas))) +
geom_point(size = 1, position = position_jitter(w = 0.002, h = 0), pch = 18) +
mytheme + ylab("Metapopulation survival") +
scale_color_discrete(Label_compLegend) +
scale_shape_discrete(Label_compLegend) +
xlab("environmental variation")+
scale_y_log10(breaks = c(5, 10, 30, 100, 500)) +
stat_smooth(method = "lm", formula = y ~ x + I(x^2), se = FALSE)
dev.off()
sub_adDsp0.8 <- subset(subDispFile, ad_dsp_fd == 0.8 & Comp_meas == 0.2)
sub_adDsp0.8 <- subset(subDispFile, ad_dsp_fd == 0.8)
nrow(sub_adDsp0.8)
my_nls <- nls(log_metPopAgeMax ~ 2.7/(1+exp(-k * (input_var - z))) , data = sub_adDsp0.8, start = list(k = 1, z = 0.2))
my_seq <- seq(0, 0.8, by = 0.001)
my_pdt_nls<- predict(my_nls, list(log_metPopAgeMax = my_seq)) # not working
points(x = sub_adDsp0.8$input_var, y = sub_adDsp0.8$log_metPopAgeMax, pch = 9)
plot(x = seq(0, 0.8, by = 0.001), pdt_nls, pch = ".")
png("RuthSync/Thesis/Presentation/3_compdispNoEnv_adDsp0pt8.png", width = 1950, height = 600, units = "px", res = 200)
ggplot(sub_adDsp0.8 , aes(x = input_var, y = metPopAgeMax, color = as.factor(Comp_meas))) +
geom_point(size = 2, position = position_jitter(w = 0.002, h = 0), pch = 18) +
mytheme + ylab("Metapopulation survival") +
xlab("environmental variation")+
scale_y_log10(breaks = c(5, 10, 30, 100, 500)) +
geom_smooth(se = FALSE, method = "lm", formula = y ~ x + I(x^2))
dev.off()
stat_smooth(method = 'nls', se = FALSE,
method.args = list(
formula = y ~ 2.7/(1+exp(-k * (x - z))),
start = list(k = 1, z = 0.2)
))
scale_y_log10(breaks = c(5, 10, 30, 100, 500)) +
############## Dispersal Increases ###################################
subDispFile <- subset(importDispFile, max_no_off == no_off)
subDispFile <- subset(subDispFile, Comp_meas != 0.5 & input_var != 0.05 & input_var != 0.15)
dispEnv <- subset(subDispFile, (ad_dsp_fd == 0.6 & Comp_meas == 0) | (ad_dsp_fd == 0.8 & Comp_meas == 0) | (ad_dsp_fd == 0.8 & Comp_meas == 0.2))
dispEnv$all_ave_num_disp <- ifelse(is.na(dispEnv$all_ave_num_disp) == TRUE , 0, dispEnv$all_ave_num_disp)
dispEnv$Legend <- ifelse(dispEnv$ad_dsp_fd == 0.6 & dispEnv$Comp_meas == 0, "comp=0.0 and dispersal size=0.6",
ifelse(dispEnv$ad_dsp_fd == 0.8 & dispEnv$Comp_meas == 0, "comp=0.0 and dispersal size=0.8",
ifelse(dispEnv$ad_dsp_fd == 0.8 & dispEnv$Comp_meas == 0.2, "comp=0.2 and dispersal size=0.8", "MISTAKE")))
dispSum <- summarySE(dispEnv, measurevar="all_ave_num_disp", groupvars=c("input_var","Legend"))
png("RuthSync/Thesis/Presentation/3_compDispIncreaes.png", width = 1500, height = 800, units = "px", res = 200)
ggplot(dispSum, aes(x=input_var, y=all_ave_num_disp, color = Legend)) +
geom_errorbar(aes(ymin=all_ave_num_disp-se, ymax=all_ave_num_disp+se), width=.03) +
geom_point(size = 2) + mytheme+
geom_line() +
xlab("Environmental variation") + ylab("Number of dispersing colonies") +
scale_shape_manual(values=c(0, 2, 19)) +
scale_color_discrete("Competition and\ndispersal size") +
scale_shape_discrete("Competition and\ndispersal size")
dev.off()
|
5d3e30a1f8931a89eec6a73b86a3820577956111 | e055378297084fa87419c17ae813cb288f94d6dc | /importar_datos/tabular/01-tabular-data.R | e4ee2c45fc07eca51e36db8104c704455b214709 | [] | no_license | diosimar/ciencia-de-datos-con-r | 48cf041582fc7f03e5c8be3164253779d026e8f8 | 3228589ec1c605e490c835ec18b143e8b3ad600d | refs/heads/master | 2023-03-16T20:37:53.446037 | 2018-04-16T13:46:09 | 2018-04-16T13:46:09 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 417 | r | 01-tabular-data.R |
# Importar Archivos de Texto
library(readr)
csv <- read_csv("data/Water_Right_Applications.csv")
# Importar Archivos de Excel
library(readxl)
excel <- read_excel("data/Water_Right_Applications.xls")
# Importar Archivos SPSS
library(haven)
sav <- read_sav("data/Child_Data.sav")
# Importar Archivos SAS
sas <- read_sas("data/iris.sas7bdat")
# Import Archivos STATA
stata <- read_dta("data/Milk_Production.dta")
|
43a76f3838b61dc7418a80bdd17b8872362232fe | 4e8ba753742048ff9abe1fc1cbd6962831bc0c48 | /man/cG.Rd | 6a3cbc1224d31e465104ad7c81673c54908e1ad9 | [
"MIT"
] | permissive | CJBarry/DNAPL | b8af12be56e15ce0404f977b8aa9f67d5ed4330c | 30f287e46b0b4f3cbe5e20c35982f4dc7452c32a | refs/heads/master | 2021-01-23T00:53:20.619082 | 2017-08-01T21:49:50 | 2017-08-01T21:49:50 | 85,844,501 | 0 | 0 | null | null | null | null | UTF-8 | R | false | true | 1,707 | rd | cG.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/DNST_model.R
\name{cst-cnvG}
\alias{cnvG.DNmodel}
\alias{cst-cnvG}
\alias{cstG.DNmodel}
\title{Constant and Convering power mass-flux relationship model}
\usage{
cstG.DNmodel(wg, wpm, hp, Gamma, Srn, Srw, phi, rho, Cs, hL,
NLAY = length(hL))
cnvG.DNmodel(wg, wpm, hp, Gamma0, Srn, Srw, phi, rho, Cs, hL,
NLAY = length(hL))
}
\arguments{
\item{wg}{numeric \code{[1]} or \code{[NLAY]};
ganglia width}
\item{wpm}{numeric \code{[1]} or \code{[NLAY]};
maximum pool width (may be \code{Inf} in the lowest layer, in which case
no DNAPL is allowed to escape)}
\item{hp}{numeric \code{[1]} or \code{[NLAY]};
pool height, or total height of pools in a layer}
\item{Gamma, Gamma0}{numeric \code{[1]} or \code{[NLAY]};
empirical source depletion parameter, positive; small values (<1) imply
a more persistent source term\cr
for \code{cstG.DNmodel}, \Gamma is constant throughout the model,
but for \code{cnvG.DNmodel}, \Gamma converges linearly from
\code{Gamma0} (at peak mass) to 1 as the NAPL mass depletes.}
\item{Srn, Srw}{numeric \code{[1]};
residual saturations of NAPL and water}
\item{phi}{numeric \code{[1]} or \code{[NLAY]};
bulk porosity of each layer}
\item{rho}{numeric \code{[1]};
solvent density (ensure consistent units, probably kg/m^3)}
\item{Cs}{numeric \code{[1]};
solvent solubility in water (ensure consistent units, probably kg/m^3
which is the same as g/l)}
\item{hL}{numeric \code{[1]} or \code{[NLAY]};
the height of each layer; note that higher layers will contain more NAPL
mass}
\item{NLAY}{integer \code{[1]};
number of layers in the DNAPL model}
}
\value{
a \link{DNAPLmodel} S4 object
}
|
adafb8b16277595791789cb85d404fa02da5632e | eac61fdb09864ed4f95222996851c656678bc5d2 | /man/breast.Rd | f2e11c11dc433495d456b88671eb6c4f02fa9ffe | [] | no_license | cran/dglars | 4b54c2ebe8101754aa7a45249a02975e868e3e74 | ba40024f96eb31f8a06133abaa008a5d4a8f1a55 | refs/heads/master | 2020-06-04T04:58:08.005888 | 2020-02-26T09:40:02 | 2020-02-26T09:40:02 | 17,695,485 | 1 | 1 | null | null | null | null | UTF-8 | R | false | false | 1,566 | rd | breast.Rd | \name{breast}
\docType{data}
\alias{breast}
\title{
Breast Cancer microarray experiment
}
\description{
This data set details microarray experiment for 52 breast cancer patients. The binary variable \code{status} is used to indicate whether or not the patient has died of breast cancer (\code{status = 0} = did not die of breast cancer, \code{status = 1} = died of breast cancer). The other variables contain the amplification or deletion of the considered genes.
Rather than measuring gene expression, this experiment aims to measure gene amplification or deletion, which refers to the number of copies of a particular DNA sequence within the genome. The aim of the experiment is to find out the key genomic factors involved in agressive and non-agressive forms of breast cancer.
The experiment was conducted by the Dr.\ John Bartlett and Dr.\ Caroline Witton in the Division of Cancer Sciences and Molecular Pathology of the University of Glasgow at the city's Royal Infirmary.
}
\usage{data(breast)}
\source{Dr. John Bartlett and Dr. Caroline Witton, Division of Cancer Sciences and Molecular Pathology, University of Glasgow, Glasgow Royal Infirmary.
}
\references{
Augugliaro L., Mineo A.M. and Wit E.C. (2013) <doi:10.1111/rssb.12000>
\emph{dgLARS: a differential geometric approach to sparse generalized linear models}, \emph{Journal of the Royal Statistical Society. Series B.}, Vol 75(3), 471-498.
Wit E.C. and McClure J. (2004, ISBN:978-0-470-84993-4)
"Statistics for Microarrays: Design, Analysis and Inference"
Chichester: Wiley.
}
\keyword{datasets}
|
3dca5d88722395bd05e7d474fd15a4895ae01517 | a5c7d31a873316639d1cb1576161bafa84fc9650 | /Assignment-5/code/que3-b.R | 2fea7f79f67850a9932fd3fc5778385bf3a2e9d8 | [] | no_license | hrushikesht/Monte-Carlo-Simulation-MA226 | c666310dadc1e6051f0b1ba44930cb5239889784 | 6471c877fa274092c2125c27ab569443df4d7302 | refs/heads/master | 2021-01-19T07:50:44.073237 | 2017-04-26T16:30:34 | 2017-04-26T16:30:34 | 87,423,351 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 507 | r | que3-b.R | n<-10
dist<-c(0.05,0.25,0.45,0.15,0.1)
cdf<-c(0.05,0.25,0.45,0.15,0.1)
sample<-vector(length=n)
for(i in 2:5)
{
cdf[i]<-cdf[i]+cdf[i-1]
}
i<-1
c<-0.45
lim<-5
while(i<=n)
{
x<-lim*runif(1)
x<-floor(x)+1
px<-dist[x]
if(c*runif(1)<px)
{
sample[i]=x
i<-i+1
}
}
# genDiscrete()
png("que3b_in_R.png")
hist(sample,breaks=50,col="red",plot=TRUE)
print(sample)
cat("\n")
cat("\nMean: ",mean(sample),"\n")
cat("Variance: ",var(sample),"\n")
cat("Max: ",max(sample),"\n")
cat("Min: ",min(sample),"\n") |
722b8ea14e3f251510a2928261e0600ecdd08033 | 940a028200ff58df2719faad500d7fc991f1d61e | /man/fPassNetworkChart.Rd | 09584675fbdf39897673caaa7ab11e25bc49f4c8 | [
"MIT"
] | permissive | thecomeonman/CodaBonito | c896c41363eab4c50e55d2c1ad66a25a25491beb | 632a1c17bfe6fa530292ce70861a51cfcaca9066 | refs/heads/master | 2023-04-08T22:09:45.765183 | 2023-04-02T05:36:56 | 2023-04-02T05:36:56 | 211,389,135 | 26 | 7 | null | null | null | null | UTF-8 | R | false | true | 1,470 | rd | fPassNetworkChart.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/fPassNetworkChart.R
\name{fPassNetworkChart}
\alias{fPassNetworkChart}
\title{Pass network ( WIP )}
\usage{
fPassNetworkChart(
dtPasses,
dtPlayerLabels,
nXLimit = 120,
nYLimit = 80,
nSegmentWidth = 1,
cFontFamily = "arial",
cForegroundColour = "red",
cBackgroundColour = "black",
cFontColour = "white"
)
}
\arguments{
\item{dtPasses}{a data.table with the columns playerId ( the player who
made the pass, ) recipientPlayerId ( the player who received the pass, )
Success ( 1/0 for whether the pass reached the recipient, ) x ( the
coordinate along the length of the pitch, 0 is defensive end, nXLimit is
offensive end, ) and y ( along the breadth of the pitch, 0 is right wing and
nYLimit is left wing. ) Refer to the dtPasses dataset packaged with the
library}
\item{dtPlayerLabels}{a data.table with the colums playerId ( same as
dtPasses, ) and playerName ( the label that the point of the respective
player should be labelled as. ) Leaving this blank will mean no labels in
the diagram. Refer to the dtPlayerLabels dataset packaged with the library.}
\item{nXLimit}{Length of the pitch}
\item{nYLimit}{Breadth of the pitch}
}
\description{
Plots a marker for each player at their median passing position, and draws
connections between players to represent the number of passes exchanged
between them
}
\examples{
fPassNetworkChart(
dtPasses,
dtPlayerLabels
)
}
|
3cddc2723a5b14619453ffc25fb9d2740a41e4b9 | 6ba3c2e9be2430072720856059221eff4c831216 | /R/ETCiwd.R | d636f40fb82ecdb92e70f5a5a2a11e94fedb1a62 | [] | no_license | frajaroco/PI | f6741b0bd64f3d60831f0ffbfe9482be17210103 | 1f246c7760dee2ac9cdad46bda82845624a4c1e1 | refs/heads/master | 2022-07-04T18:05:44.842120 | 2020-05-22T06:46:08 | 2020-05-22T06:46:08 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 669 | r | ETCiwd.R | ETCiwd <- function(data.eto, farms, rastera, date.start, date.end=date.start, stat.coord){
data.eto$date <- as.Date(data.eto$date)
data.search <- subset(data.eto, date >= date.start & date <= date.end)
data.stat <- sapply(1 : length(names(table(data.search$id.sta))), function(i) subset(data.search, id.stat == names(table(data.search$id.stat))[i]), simplify = FALSE)
cumsum.data <- sapply(1 : length(data.stat), function(i) sum(data.stat[[i]]$eto))
x <- stat.coord[,1]
y <- stat.coord[,2]
cumsum.eto <- data.frame(names(table(data.search$id.sta)),x,y,cumsum.data)
names(cumsum.eto) <- c("id.stat","x","y","eto")
coordinates(cumsum.eto) = ~ x + y
return(cumsum.eto)}
|
e114fbe5755ae5e92cc449b89e814f81c8262555 | 8420b44814113c5b984edd2d565195062a3eaef0 | /src/reddit/award.R | c98802eee8c216201172fd8f9dbd6c7bb24c8630 | [
"Apache-2.0"
] | permissive | beaudryjp/sna_fcaR | fa22489515a7a63e4d850923874419b547ff6399 | c5de324ca9140b3d51df026d6271d5dbe9a64ea7 | refs/heads/main | 2023-07-17T08:05:31.249149 | 2021-09-05T15:39:32 | 2021-09-05T15:39:32 | 347,778,603 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 2,628 | r | award.R |
# STRUCTURES ######################################
### Returns the dataframe structure for awards
### @parameters: none
### @returns: dataframe
df_award = function(){
data <- data.frame(post_id = character(), coin_id = character(), quantity = integer())
return(data)
}
### Returns the dataframe structure for coins
### @parameters: none
### @returns: dataframe
df_coin = function(){
data <- data.frame(id = character(), name = character(), description = character(),
coin_price = integer(), coin_reward = integer())
return(data)
}
# DATABASE OPERATIONS ######################################
### Insert awards from a post into the database
### @parameters: awards = dataframe
### @returns: none
award.insert_in_db = function(data){
values <- paste0("('", data$post_id, "','", data$coin_id, "',", data$quantity, ")", collapse = ", ")
query <- paste0("INSERT IGNORE INTO awards_post VALUES ", values, ";")
# database$insert(query)
db.insert(query)
}
### Insert coins into the database
### @parameters: coin = dataframe
### @returns: none
coin.insert_in_db = function(data){
values <- paste0("('", data$id, "','",
data$name, "','",
data$description, "',",
data$coin_price, ",",
data$coin_reward,")",
collapse = ", ")
query <- paste0("INSERT IGNORE INTO coin VALUES ", values, ";")
# database$insert(query)
db.insert(query)
}
# DATA MANIPULATION ######################################
### Insert awards from a corresponding post
### @parameters: data = dataframe
### @returns: none
award.process = function(data){
new_data <- data[data$post_exists == FALSE,]
if(length(new_data$all_awardings) > 0){
coin <- df_coin()
award_post <- df_award()
for(row in 1:length(new_data$all_awardings)){
if(!is.null(nrow(new_data[row, ]$all_awardings[[1]])) && nrow(new_data[row, ]$all_awardings[[1]]) > 0){
award_post <- award_post %>%
add_row(post_id = new_data[row, ]$id,
coin_id = new_data$all_awardings[[row]]$id,
quantity = new_data$all_awardings[[row]]$count)
coin <- coin %>%
add_row(id = new_data$all_awardings[[row]]$id,
name = gsub("'","" , new_data$all_awardings[[row]]$name ,ignore.case = TRUE),
description = escape_strings(new_data$all_awardings[[row]]$description),
coin_price = new_data$all_awardings[[row]]$coin_price,
coin_reward = new_data$all_awardings[[row]]$coin_reward)
}
}
if(nrow(coin) > 0) coin.insert_in_db(coin %>% distinct())
if(nrow(award_post) > 0) award.insert_in_db(award_post)
}
}
|
bbe4bfe63690e099831f6cdbac8a4360bb7595dd | b1ee6ba6c754e8a44d2baab99b0a6565ef19d628 | /get_all_catch_data.r | 3d54bcde23c182d9bfb00eca293357d7231c821e | [] | no_license | jasmyace/CAMP_RST | 527c48a01c5cd9992ad2282f37d0ded70883591f | 1681df75097bb99279e681458e0c6a432ebfcd37 | refs/heads/master | 2021-01-17T22:43:53.743451 | 2015-10-01T19:23:41 | 2015-10-01T19:23:41 | 26,222,751 | 0 | 0 | null | 2015-10-01T18:26:31 | 2014-11-05T14:19:46 | R | UTF-8 | R | false | false | 2,280 | r | get_all_catch_data.r | F.get.all.catch.data <- function( site, taxon, min.date, max.date ){
#
# Fetch the catch data for a SINGLE TAXON from an Access data base.
# This function retrieves all catch data for
#
# input:
# db = full path and name of the Access data base to retrieve data from
# tables = vector with named components containing names
# of the table in db to pull values from
# site = site ID of place we want to do estimates for.
# taxon = the taxon number (from luTaxon) to retrieve.
# min.date = minimum date for data to include. This is a text string in the format %Y-%m-%d, or YYYY-MM-DD
# max.date = maximum date for data to include. Same format as min.date
#
# To be included in the catch data, a record has to be from the site,
# of the correct taxon, of the correct run, and between min and max dates.
#
# *****
nvisits <- F.buildReportCriteria( site, min.date, max.date )
if( nvisits == 0 ){
warning("Your criteria returned no trapVisit table records.")
return()
}
# *****
# Open ODBC channel
db <- get( "db.file", env=.GlobalEnv )
ch <- odbcConnectAccess(db)
# *****
# This SQL file develops the hours fished and TempSamplingSummary table
F.run.sqlFile( ch, "QrySamplePeriod.sql", R.TAXON=taxon )
# *****
# This SQL generates the sum chinook by trap series of queries
F.run.sqlFile( ch, "QrySumChinookByTrap.sql", R.TAXON=taxon )
# *****
# Now, fetch the result
visit <- sqlFetch( ch, "TempChinookSampling_i_final" )
F.sql.error.check(visit)
# ******
# Fetch run name
#run.name <- sqlQuery( ch, paste("SELECT run AS runName FROM luRun WHERE runID=", run ))
#F.sql.error.check(run.name)
# Assign attributes
attr(visit, "siteID" ) <- site
attr(visit, "site.name") <- visit$Site[1]
attr(visit, "site.abbr") <- visit$siteAbbreviation[1]
#attr(visit, "runID") <- run
#attr(visit, "run.name") <- run.name
#attr(visit, "run.season") <- run.season
#attr(visit, "site.stream") <- site.stream
attr(visit, "subsites") <- unique(visit$TrapPositionID)
#attr(visit, "taxonID" ) <- taxon.string
#attr(visit, "species.name") <- sp.commonName
#
cat("First 20 records of catch data frame...\n")
if( nrow(visit) >= 20 ) print( visit[1:20,] ) else print( visit )
#f.banner("F.get.catch.data - Complete")
visit
}
|
d5480976172ce94d46aa468918f8f450091aa5b8 | 789c0c3b0fc4abe910453a520ff6a0392b43d30d | /PrimRecur/paired_patient_CNA_traj.r | fb270a8c62029b1ca3bcaa3e7c9721638e8c3e63 | [] | no_license | SMC1/JK1 | 7c71ff62441494c09b148b66b4d766377c908b4b | db8ec385468f8ff6b06273d6268e61ff4db3701f | refs/heads/master | 2016-09-05T17:29:15.217976 | 2015-04-29T05:58:02 | 2015-04-29T05:58:02 | 6,700,479 | 1 | 1 | null | null | null | null | UTF-8 | R | false | false | 3,223 | r | paired_patient_CNA_traj.r | inDirName = '/EQL1/PrimRecur/paired'
inSegDirName = '/data1/IRCR/CGH/seg/seg/link'
graphicsFormat = ''
cnaMaxAbs = 3
chrLenDF = read.table('/data1/Sequence/ucsc_hg19/chromsizes_hg19.txt',header=F)
totChrLen = 0
for (chr in c(1:22,c('X','Y','M'))) {
totChrLen = totChrLen + chrLenDF[chrLenDF[,1]==sprintf('chr%s',chr),2]
}
drawTraj <- function(
sId,
lColCommon=NaN,
cnaMaxAbs=3
)
{
df = read.table(sprintf('%s/%s.seg',inSegDirName,sId),header=T)
plot(c(0,totChrLen),c(0,0),ylab='CN (log2)',xlim=c(0,totChrLen), ylim=c(-cnaMaxAbs,cnaMaxAbs), type='l',pch=22,lty=2,axes=T,ann=T,xaxs='i',yaxs='i',xaxt='n',cex.lab=1)
totLen = 0
for (chr in c(1:22,c('X','Y','M'))) {
chrLen = as.numeric(chrLenDF[chrLenDF[,1]==sprintf('chr%s',chr),2])
df_ft = df[df$chrom==chr,c(3,4,6)]
df_ft = df_ft[order(df_ft$loc.start),]
text(totLen,-cnaMaxAbs+cnaMaxAbs*2*0.03,chr,adj=c(0,0),col='grey',cex=1.1)
if (nrow(df_ft) > 0) {
for (j in 1:nrow(df_ft)) {
if (is.nan(lColCommon)){
if (df_ft[j,3]>=0.2) lCol = 'red'
else if (df_ft[j,3]<=-0.2) lCol = 'blue'
else lCol = 'black'
}else {
lCol = lColCommon
}
if (df_ft[j,3]>=cnaMaxAbs) {
lWth = 6
df_ft[j,3] = cnaMaxAbs
} else if (df_ft[j,3]<=-cnaMaxAbs) {
lWth = 6
df_ft[j,3] = -cnaMaxAbs
} else {
lWth = 3
}
lines(c(df_ft[j,1],df_ft[j,2])+totLen,c(df_ft[j,3],df_ft[j,3]),lwd=lWth,col=lCol)
}
}
abline(v=totLen,pch=22,lty=2,col='grey')
totLen = totLen + chrLen
}
abline(v=totLen,pch=22,lty=2,col='grey')
}
paired_CNA_traj <- function(
inDirName,
inSegDirName,
graphicsFormat='png'
)
{
df = read.table(sprintf('%s/paired_df_CNA.txt',inDirName),header=TRUE)
sIdPairDF = unique(df[,1:2])[,]
sIdPriL = as.vector(sIdPairDF[,1])
sIdRecL = as.vector(sIdPairDF[,2])
for (i in 1:nrow(sIdPairDF)) {
sId_p = sIdPriL[i]
sId_r = sIdRecL[i]
if (graphicsFormat == 'png') {
png(sprintf("%s/CNA_traj/paired_CNA_traj_%s_%s.png", inDirName,sId_p,sId_r))
} else if (graphicsFormat== 'pdf') {
pdf(sprintf("%s/CNA_traj/paired_CNA_traj_%s_%s.pdf", inDirName,sId_p,sId_r))
}
par(mfrow=c(3,1),mgp=c(2,1,0))
par(oma=c(1,2,1,1))
par(mar=c(1,3,0,0))
drawTraj(sId_p); text(totChrLen*0.02,cnaMaxAbs-cnaMaxAbs*2*0.03,sprintf('%s',sId_p),adj=c(0,1),cex=1.1)
drawTraj(sId_r); text(totChrLen*0.02,cnaMaxAbs-cnaMaxAbs*2*0.03,sprintf('%s',sId_r),adj=c(0,1),cex=1.1)
drawTraj(sId_p,'green'); par(new=T); drawTraj(sId_r,'magenta'); text(totChrLen*0.02,cnaMaxAbs-cnaMaxAbs*2*0.03,sprintf('%s-%s',sId_p,sId_r),adj=c(0,1),cex=1)
r = cor.test(df[df$sId_p==sId_p,'val_p'], df[df$sId_r==sId_r,'val_r'])$estimate
text(totChrLen*0.02,cnaMaxAbs-cnaMaxAbs*2*0.12,sprintf('R = %.2f',r),adj=c(0,1),cex=1.1)
if (graphicsFormat=='png' || graphicsFormat=='pdf'){
dev.off()
}
}
}
# for (fmt in c('')) paired_CNA_traj(inDirName,inSegDirName,fmt)
for (fmt in c('png','pdf','')) paired_CNA_traj(inDirName,inSegDirName,fmt)
|
4b1a57a22e7513e85f878c68d9350acc07487de8 | ffdea92d4315e4363dd4ae673a1a6adf82a761b5 | /data/genthat_extracted_code/ari/examples/ari_stitch.Rd.R | f3668cd671f23e9e8bfeb484cc31bd41051660c6 | [] | no_license | surayaaramli/typeRrh | d257ac8905c49123f4ccd4e377ee3dfc84d1636c | 66e6996f31961bc8b9aafe1a6a6098327b66bf71 | refs/heads/master | 2023-05-05T04:05:31.617869 | 2019-04-25T22:10:06 | 2019-04-25T22:10:06 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 378 | r | ari_stitch.Rd.R | library(ari)
### Name: ari_stitch
### Title: Create a video from images and audio
### Aliases: ari_stitch
### ** Examples
## Not run:
##D
##D library(tuneR)
##D library(purrr)
##D
##D slides <- c("intro.jpeg", "equations.jpeg", "questions.jpeg")
##D sound <- map(c("rec1.wav", "rec2.wav", "rec3.wav"), readWave)
##D
##D ari_stitch(slides, sound)
##D
## End(Not run)
|
b155647bedd516542f6959fd6f86c7f93ced2091 | 0a906cf8b1b7da2aea87de958e3662870df49727 | /diversityForest/inst/testfiles/numSmaller/libFuzzer_numSmaller/numSmaller_valgrind_files/1610037434-test.R | d55d5de1fbe5cc9b05c66ae35df9cf29c3c214b1 | [] | no_license | akhikolla/updated-only-Issues | a85c887f0e1aae8a8dc358717d55b21678d04660 | 7d74489dfc7ddfec3955ae7891f15e920cad2e0c | refs/heads/master | 2023-04-13T08:22:15.699449 | 2021-04-21T16:25:35 | 2021-04-21T16:25:35 | 360,232,775 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,050 | r | 1610037434-test.R | testlist <- list(reference = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), values = c(-5.13705316173747e-195, -5.04975683349975e-195, -6.53043680162072e-196, -5.04975683349975e-195, 8.91043534376365e+194, -5.04962232345372e-195, 3.52953817726726e+30, 3.52953696534134e+30, 3.52953696534134e+30, 3.52953696534134e+30, 3.52953696534134e+30, 3.52953696534134e+30, 3.52953696534134e+30, -6.95031827487957e-308, -4.49280101835028e+307, 3.25111344630782e-111, 3.52953696534134e+30, 3.52953696534134e+30, 3.81752867881136e-310, -5.48612406879369e+303, NaN, -3.45993240747451e+296, NaN, 2.97403240769821e+284, 8.28904556439245e-317, 0, 0, 0, -1.34095520796864e+295, NaN, 9.91641345704528e+107, NaN, NaN, NaN, NaN, 7.25538122530665e-304, NaN))
result <- do.call(diversityForest:::numSmaller,testlist)
str(result) |
e46d98ca8cf959e35d5690d13a6d53907591d663 | 3f80ff92034075fb293f1753c698fdbab65b08f0 | /Rscripts/6.0_SummarizePrioritizationTargets.R | 27106ca7d6e58b995d8c43b02bb534ca19dc66fa | [
"MIT"
] | permissive | ApexRMS/a238 | da66e9b5c09bbd0304d96bda298a009eea590c3e | 9da3fb4946c151419d1d9e77734458f42307c72e | refs/heads/master | 2023-03-30T17:50:38.619191 | 2021-04-13T13:49:57 | 2021-04-13T13:49:57 | 295,523,122 | 0 | 0 | null | 2021-04-13T13:49:58 | 2020-09-14T19:51:29 | R | UTF-8 | R | false | false | 6,990 | r | 6.0_SummarizePrioritizationTargets.R | ## Workspace ---------------------------------------------------------
options(tibble.width = Inf)
# Packages
library(tidyverse)
library(raster)
## Directories
rawDataDir <- paste0("Data/Raw")
procDataDir <- paste0("Data/Processed")
##Load files ---------------------------------------------------------
# Natural Areas in Monteregie with LULC codes
naturalAreasMonteregie <- raster(file.path(procDataDir, "LULCnatural_FocalArea.tif"))
# Protected areas in Monteregie
protectedAreasMonteregie <- raster(file.path(procDataDir, "protectedAreasTerrestrial_FocalArea.tif"))
# Ecoregions in Monteregie
ecoregions <- raster(file.path(procDataDir, "ecoregions_FocalArea.tif")) %>%
crop(., naturalAreasMonteregie)
ecoregions[ecoregions==-9999]<-NA
ecoregions[ecoregions==0]<-NA
# Ecoregions - zone1 Adirondacks, zone 3 = StL lowlands, Zone 4 = appalachians
ecoregionList <- unique(ecoregions)
# Monteregie extent
# Make a Monteregie study area
studyAreaMonteregie <- Which(ecoregions>0)
# Make a binary version of natural areas for Monteregie
naturalAreasBinaryMonteregie <- Which(naturalAreasFocal)
# Make a protected natural areas map for Monteregie
protectedNaturalAreasMonteregie <- mask(naturalAreasBinaryMonteregie, protectedAreasMonteregie)
# Divide landscapes into 3 ecoregion zones (1, 3 and 4)
ecoregion1 <- calc(ecoregions, fun=function(x){ifelse(x==1, 1, NA)})
ecoregion3 <- calc(ecoregions, fun=function(x){ifelse(x==3, 1, NA)})
ecoregion4 <- calc(ecoregions, fun=function(x){ifelse(x==4, 1, NA)})
#
naturalAreas1 <- mask(naturalAreasBinaryMonteregie, ecoregion1)
naturalAreas3 <- mask(naturalAreasBinaryMonteregie, ecoregion3)
naturalAreas4 <- mask(naturalAreasBinaryMonteregie, ecoregion4)
#
protectedAreas1 <- mask(protectedAreasMonteregie, ecoregion1)
protectedAreas3 <- mask(protectedAreasMonteregie, ecoregion3)
protectedAreas4 <- mask(protectedAreasMonteregie, ecoregion4)
#
protectedNaturalAreas1 <- mask(naturalAreasBinaryMonteregie, protectedAreas1)
protectedNaturalAreas3 <- mask(naturalAreasBinaryMonteregie, protectedAreas3)
protectedNaturalAreas4 <- mask(naturalAreasBinaryMonteregie, protectedAreas4)
# Tabular summaries for Monteregie and ecoregions
monteregieSummary <- tibble(Name = "Monteregie",
ID = NA,
TotalPixels = cellStats(studyAreaMonteregie, sum),
NaturalAreaPixels = cellStats(naturalAreasBinaryMonteregie, sum),
ProtectedAreaPixels = cellStats(protectedAreasMonteregie, sum),
ProtectedNaturalAreaPixels = cellStats(protectedNaturalAreasMonteregie, sum))
ecoregion1Summary <- tibble(Name = "Ecoregion1",
ID = 1,
TotalPixels = cellStats(ecoregion1, sum),
NaturalAreaPixels = cellStats(naturalAreas1, sum),
ProtectedAreaPixels = cellStats(protectedAreas1, sum),
ProtectedNaturalAreaPixels = cellStats(protectedNaturalAreas1, sum))
ecoregion3Summary <- tibble(Name = "Ecoregion3",
ID = 3,
TotalPixels = cellStats(ecoregion3, sum),
NaturalAreaPixels = cellStats(naturalAreas3, sum),
ProtectedAreaPixels = cellStats(protectedAreas3, sum),
ProtectedNaturalAreaPixels = cellStats(protectedNaturalAreas3, sum))
ecoregion4Summary <- tibble(Name = "Ecoregion4",
ID = 4,
TotalPixels = cellStats(ecoregion4, sum),
NaturalAreaPixels = cellStats(naturalAreas4, sum),
ProtectedAreaPixels = cellStats(protectedAreas4, sum),
ProtectedNaturalAreaPixels = cellStats(protectedNaturalAreas4, sum))
overallSummary <- bind_rows(monteregieSummary, ecoregion1Summary, ecoregion3Summary, ecoregion4Summary) %>%
mutate(NaturalAreaPercent = NaturalAreaPixels/TotalPixels*100) %>%
mutate(ProtectedAreaPercent = ProtectedAreaPixels/TotalPixels*100) %>%
mutate(ProtectedNaturalAreaPercent = ProtectedNaturalAreaPixels/TotalPixels*100) %>%
mutate(TargetPixels0.05 = 0.05*TotalPixels) %>%
mutate(TargetPixels0.10 = 0.10*TotalPixels) %>%
mutate(TargetPixels0.17 = 0.17*TotalPixels) %>%
mutate(PixelsToAdd0.05 = TargetPixels0.05 - ProtectedAreaPixels) %>%
mutate(PixelsToAdd0.10 = TargetPixels0.10 - ProtectedAreaPixels) %>%
mutate(PixelsToAdd0.17 = TargetPixels0.17 - ProtectedAreaPixels) %>%
mutate(TargetNaturalAreaPercent0.05 = TargetPixels0.05/NaturalAreaPixels*100) %>%
mutate(TargetNaturalAreaPercent0.10 = TargetPixels0.10/NaturalAreaPixels*100) %>%
mutate(TargetNaturalAreaPercent0.17 = TargetPixels0.17/NaturalAreaPixels*100) %>%
mutate(TargetAddNaturalAreaPixels0.05 = TargetPixels0.05 - ProtectedNaturalAreaPixels) %>%
mutate(TargetAddNaturalAreaPixels0.10 = TargetPixels0.10 - ProtectedNaturalAreaPixels) %>%
mutate(TargetAddNaturalAreaPixels0.17 = TargetPixels0.17 - ProtectedNaturalAreaPixels) %>%
mutate(TargetAddNaturalAreaPercent0.05 = TargetAddNaturalAreaPixels0.05/NaturalAreaPixels*100) %>%
mutate(TargetAddNaturalAreaPercent0.10 = TargetAddNaturalAreaPixels0.10/NaturalAreaPixels*100) %>%
mutate(TargetAddNaturalAreaPercent0.17 = TargetAddNaturalAreaPixels0.17/NaturalAreaPixels*100)
write_csv(overallSummary, file.path(procDataDir, "TargetAreaSummary.csv"))
# Calculate zone-specific % protected areas for deliverables (as # of cells)
zone1LULC <- calc(ecoregionsLULC, fun=function(x){ifelse(x==1, 1, NA)})
zone3LULC <- calc(ecoregionsLULC, fun=function(x){ifelse(x==3, 1, NA)})
zone4LULC <- calc(ecoregionsLULC, fun=function(x){ifelse(x==4, 1, NA)})
#
zonePA1 <- cellStats(protectedAreasNA1, sum, na.rm=T)#/cellStats(zone1LULC, sum, na.rm=T)
zonePA3 <- cellStats(protectedAreasNA3, sum, na.rm=T)#/cellStats(zone3LULC, sum, na.rm=T)
zonePA4 <- cellStats(protectedAreasNA4, sum, na.rm=T)#/cellStats(zone4LULC, sum, na.rm=T)
## 3) Set prioritization targets ----------------------------------------------------------------
## Budget - Change budget as desired ##
Budget <- 0.1
# Identify all natural areas available for prioritization and omit PA areas
costLayer1 <- naturalAreasBinaryFocal1 %>%
mask(., protectedAreasNA1, inv=TRUE) #omit protected area cells
costLayer3 <- naturalAreasBinaryFocal3 %>%
mask(., protectedAreasNA3, inv=TRUE) #omit protected area cells
costLayer4 <- naturalAreasBinaryFocal4 %>%
mask(., protectedAreasNA4, inv=TRUE) #omit protected area cells
# Calculate ecoregion budgets, set by by ecoregion size (number of natural area pixels in zone)
NumSitesGoal1 <- round((Budget * cellStats(zone1LULC, sum, na.rm=T)), 0) - zonePA1
NumSitesGoal1 <- ifelse(NumSitesGoal1 <= 0, 1, NumSitesGoal1)
NumSitesGoal3 <- round((Budget * cellStats(zone3LULC, sum, na.rm=T)), 0) - zonePA3
NumSitesGoal3 <- ifelse(NumSitesGoal3 <= 0, 1, NumSitesGoal3)
NumSitesGoal4 <- round((Budget * cellStats(zone4LULC, sum, na.rm=T)), 0) - zonePA4
NumSitesGoal4 <- ifelse(NumSitesGoal4 <= 0, 1, NumSitesGoal4) |
e725aec83c7df86740b78acfef9f0fadcabecb78 | 2cdb135e648cbf6f78a5b55b424f8bdb13f5c140 | /scripts/rawDocStats.R | 2748d907f87bb9432d67ef0eb9cb6fc76514eb00 | [] | no_license | Fairlane100/SOTL-project | 89c234d5078ea1b9d110791cd688aafb99f9d150 | 1ea832f0e39b96836c2e916a16ffa43bc11a574c | refs/heads/master | 2021-01-20T19:42:02.219274 | 2016-12-01T20:15:57 | 2016-12-01T20:15:57 | 46,145,850 | 0 | 0 | null | 2016-09-16T18:46:47 | 2015-11-13T20:35:12 | C# | UTF-8 | R | false | false | 774 | r | rawDocStats.R | ## Calculate stats of the documentMetaData.csv contents.
# report stats in some form.
#doc.df <- read.csv(file = "documentMetaData.csv", stringsAsFactors = FALSE)
count <- dim(doc.df)[1]
tna <- length(which(is.na(doc.df$title)))
ana <- length(which(is.na(doc.df$authors)))
yna <- length(which(is.na(doc.df$year)))
sna <- length(which(is.na(doc.df$src)))
ina <- length(which(is.na(doc.df$id)))
kna <- length(which(is.na(doc.df$keywords)))
bna <- length(which(is.na(doc.df$abstract)))
str <- paste("number of documents:",count,"\n",
"missing titles:",tna,"\n",
"missing authors:",ana,"\n",
"missing year:",yna, "\n",
"missing source:",sna,"\n",
"missing id:",ina,"\n",
"missing keywords:",kna,"\n",
"missing abstract:",bna)
cat(str) |
16dd73d1181446a80c0557a5c1cccfb12eb26b53 | 21389b192885261b990d6fd9c1e910f0e2f0f4bd | /scripts/script18_now_degree_days_10yr.R | 121295c4ad509e2d96252b62b3855531c861b38c | [
"CC0-1.0"
] | permissive | ChuckBV/ms-lost-hills-areawide-y06-to-y15 | 6edab930a49c4393fa1f4e121ebb033bb93a5cb1 | c4d7543f1a79bd42f6b7a215619f43e36ba3bacf | refs/heads/main | 2023-03-05T11:25:04.089391 | 2021-02-21T04:59:19 | 2021-02-21T04:59:19 | 335,468,449 | 0 | 0 | null | 2021-02-21T04:53:33 | 2021-02-03T01:05:33 | R | UTF-8 | R | false | false | 7,660 | r | script18_now_degree_days_10yr.R | #===========================================================================#
# script18_now_degree_days_10yr.R
#
# Exploratory script examining whether temperature or other factors could
# be identified as strongly influencing whether there was more damage in
# NP than MO or vice-versa. Degree-days did not seem to be a factor, and
# it did not appear that there were one or a few blocks that were
# pre-disposed for damage in one variety compared to the other.
#
# 1. Upload NOW degree-day data for study period (line 20)
# - Examine dd by year at certain Julian dates
# 2. Upload damage data for Nonpareil and Monterey (line 110)
# - Examines whether there was a treatment x block pattern
# in which variety gets greater damage
# - t-test for Jun 15, reported in paper, is at line 203
# 3. Plot dd vs Julian for ead of the 10 years (line 239)
#
#===========================================================================#
library(tidyverse) # dplyr used to select and modify common/imp variables
library(lubridate) # for work with date format
#-- 1. Upload NOW degree-day data for study period -------------------------
ddf_lh_10yr <- read_csv("./data/now_deg_days_f_lost_hills_2005_to_2015.csv")
ddf_lh_10yr
### Select Jun 15
ddf_jun15 <- ddf_lh_10yr %>%
select(station,date,yr,julian,accumulated_dd) %>%
filter(julian == 167)
### Is there an observable warming trend over the decade?
plot(accumulated_dd ~ yr, data = ddf_jun15)
m1 <- lm(accumulated_dd ~ yr, data = ddf_jun15)
summary(m1) # P = 0.13, rsqr = 0.15
# No
ddf <- ddf_jun15 %>%
select(yr,accumulated_dd)
ddf <- ddf %>%
filter(yr > 2005) %>%
rename(Year = yr,
now_ddf = accumulated_dd)
ddf
# A tibble: 10 x 2
# Year now_ddf
# <dbl> <dbl>
# 1 2006 1122.
# 2 2007 1368.
# 3 2008 1137.
# 4 2009 1285.
# 5 2010 974.
# 6 2011 879.
# 7 2012 1221.
# 8 2013 1412.
# 9 2014 1558.
# 10 2015 1475.
### Try again with August 1
ddf_aug1 <- ddf_lh_10yr %>%
select(station,date,yr,julian,accumulated_dd) %>%
filter(julian == 214)
ddf_aug1 <- ddf_aug1 %>%
filter(yr > 2005) %>%
select(yr,accumulated_dd) %>%
rename(Year = yr,
ddf_aug01 = accumulated_dd)
ddf_aug1
# A tibble: 10 x 2
# Year ddf_aug01
# <dbl> <dbl>
# 1 2006 2344.
# 2 2007 2451.
# 3 2008 2275.
# 4 2009 2405.
# 5 2010 2025.
# 6 2011 1905.
# 7 2012 2214.
# 8 2013 2520.
# 9 2014 2686.
# 10 2015 2585.
### Try again with September 1
ddf_sep1 <- ddf_lh_10yr %>%
select(station,date,yr,julian,accumulated_dd) %>%
filter(julian == 245)
ddf_sep1 <- ddf_sep1 %>%
filter(yr > 2005) %>%
select(yr,accumulated_dd) %>%
rename(Year = yr,
ddf_sep01 = accumulated_dd)
ddf_sep1
# A tibble: 10 x 2
# Year ddf_sep01
# <dbl> <dbl>
# 1 2006 3021.
# 2 2007 3196.
# 3 2008 3039.
# 4 2009 3099.
# 5 2010 2680.
# 6 2011 2582.
# 7 2012 2975.
# 8 2013 3253.
# 9 2014 3412.
# 10 2015 3303.
#-- 2. Upload damage data for Nonpareil and Monterey ------------------------
windrow_interior <- read_csv("./data/windrow_interior_dmg_y06_to_y15_out_to_sas.csv")
windrow_interior
### The following are from script12
var_by_yr3 <- windrow_interior %>%
filter(Variety %in% c("NP","MO") & Trt_cat == "insecticide") %>%
group_by(Year,block,Variety) %>%
summarise(pctNOW = mean(pctNOW, na.rm = TRUE)) %>%
pivot_wider(names_from = Variety, values_from = pctNOW) %>%
mutate(dom_var = ifelse(NP > MO,"NP","MO"))
var_by_yr3
# A tibble: 60 x 4
# Groups: Year, block [60]
# Year block MO NP
# <dbl> <dbl> <dbl> <dbl>
# 1 2006 24.1 1.26 1.17
# 2 2006 24.2 4.30 2.61
# 3 2006 24.3 2.04 0.865
length(unique(var_by_yr3$block))
# [1] 18
### Create an index that is the ration of NP to total damage
var_by_yr3 <- var_by_yr3 %>%
mutate(np_index = NP/(NP+MO))
x <- var_by_yr3 %>%
ungroup(.) %>%
mutate(Year = factor(Year, levels = unique(Year)),
block = factor(block, levels = unique(block)))
### Plot index by year (obs = block)
ggplot(x, aes(x = Year, y = np_index)) +
geom_boxplot()
### Plot index by block (obs = year)
ggplot(x, aes(x = block, y = np_index)) +
geom_boxplot()
m1 <- lm(np_index ~ Year + block, data = x)
Anova(m1)
# Note: model has aliased coefficients
# sums of squares computed by model comparison
# Anova Table (Type II tests)
#
# Response: np_index
# Sum Sq Df F value Pr(>F)
# Year 3.2116 8 7.6983 1.239e-05 ***
# block 0.8171 16 0.9793 0.5004
# Residuals 1.6166 31
# ---
# Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘
# Sloppy, but strongly suggests that this is not about box effects
var_by_yr3
# A tibble: 10 x 4
# Groups: Year [10]
# Year NP MO dom_var
# <dbl> <dbl> <dbl> <chr>
# 1 2006 1.09 2.02 Mo
# 2 2007 0.481 0.628 Mo
# 3 2008 2.27 0.647 NP
# 4 2009 3.61 0.837 NP
# 5 2010 0.350 0.0785 NP
# 6 2011 0.0289 0.622 Mo
# 7 2012 0.914 3.32 Mo
# 8 2013 0.557 0.0933 NP
# 9 2014 2.70 1.40 NP
# 10 2015 2.35 0.434 NP
var_by_yr3b <- full_join(var_by_yr3,ddf)
var_by_yr3b %>%
arrange(now_ddf)
var_by_yr3b %>%
group_by(dom_var) %>%
summarise(nObs = n(),
mn = mean(now_ddf),
sem = FSA::se(now_ddf))
# A tibble: 2 x 4
# dom_var nObs mn sem
# <chr> <int> <dbl> <dbl>
# 1 Mo 4 1148. 103.
# 2 NP 6 1307. 89.9
t.test(now_ddf ~ dom_var, data = var_by_yr3b, var.equal = FALSE)
#
# Welch Two Sample t-test
#
# data: now_ddf by dom_var
# t = -1.1663, df = 6.915, p-value = 0.2821
# alternative hypothesis: true difference in means is not equal to 0
# 95 percent confidence interval:
# -483.0479 164.4745
# sample estimates:
# mean in group Mo mean in group NP
# 1147.685 1306.972
var_by_yr3c <- full_join(var_by_yr3,ddf_aug1)
var_by_yr3c %>%
arrange(ddf_aug01)
t.test(ddf_aug01 ~ dom_var, data = var_by_yr3c, var.equal = FALSE)
#
# Welch Two Sample t-test
#
# data: ddf_aug01 by dom_var
# t = -1.2216, df = 6.6265, p-value = 0.2635
# alternative hypothesis: true difference in means is not equal to 0
# 95 percent confidence interval:
# -553.8722 179.3889
# sample estimates:
# mean in group Mo mean in group NP
# 2228.725 2415.967
var_by_yr3d <- full_join(var_by_yr3,ddf_sep1)
var_by_yr3d %>%
arrange(ddf_sep01)
t.test(ddf_sep01 ~ dom_var, data = var_by_yr3d, var.equal = FALSE)
#-- 3. Plot ddf vs Julian ---------------------------------------------------
ddf_lh_10yr
# A tibble: 4,017 x 10
# station date air_min air_max degree_days accumulated_dd x x1 yr julian
# <chr> <date> <dbl> <dbl> <dbl> <dbl> <chr> <chr> <dbl> <dbl>
# 1 LOST_HILLS.A 2005-01-01 37 57 0.27 0.27 NA NA 2005 1
# 2 LOST_HILLS.A 2005-01-02 44 54 0 0.27 NA NA 2005 2
var_by_yr3b
# A tibble: 10 x 5
# Groups: Year [10]
# Year NP MO dom_var now_ddf
# <dbl> <dbl> <dbl> <chr> <dbl>
# 1 2006 1.09 2.02 Mo 1122.
# 2 2007 0.481 0.628 Mo 1368.
dom_var_x_yr <- var_by_yr3b %>%
select(Year,dom_var) %>%
rename(yr = Year) %>%
filter(yr > 2005)
dom_var_x_yr
ddf_lh_10yr2 <- right_join(ddf_lh_10yr,dom_var_x_yr)
ggplot(data = ddf_lh_10yr2, aes(x = julian, y = accumulated_dd, group = yr, colour = factor(yr))) +
geom_line() +
facet_grid(. ~ dom_var) +
xlim(200,250)
|
513d88ae5dc01c4f110a6fab537ff755c58d318b | ffdea92d4315e4363dd4ae673a1a6adf82a761b5 | /data/genthat_extracted_code/diffee/examples/diffee.Rd.R | 7dc8d8a6a14116618229a23adc59931f12985a28 | [] | no_license | surayaaramli/typeRrh | d257ac8905c49123f4ccd4e377ee3dfc84d1636c | 66e6996f31961bc8b9aafe1a6a6098327b66bf71 | refs/heads/master | 2023-05-05T04:05:31.617869 | 2019-04-25T22:10:06 | 2019-04-25T22:10:06 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 330 | r | diffee.Rd.R | library(diffee)
### Name: diffee
### Title: Fast and Scalable Learning of Sparse Changes in High-Dimensional
### Gaussian Graphical Model Structure
### Aliases: diffee
### ** Examples
## Not run:
##D data(exampleData)
##D result = diffee(exampleData[[1]], exampleData[[2]], 0.45)
##D plot.diffee(result)
## End(Not run)
|
689e27962009f77be4cda4dc5128a97995cd4b9a | 72d9009d19e92b721d5cc0e8f8045e1145921130 | /decido/inst/testfiles/earcut_cpp/libFuzzer_earcut_cpp/libfuzzer_logs/1609874842-inps.R | 5fe8919be835518cef668a609a5229bd336e4ba5 | [] | no_license | akhikolla/TestedPackages-NoIssues | be46c49c0836b3f0cf60e247087089868adf7a62 | eb8d498cc132def615c090941bc172e17fdce267 | refs/heads/master | 2023-03-01T09:10:17.227119 | 2021-01-25T19:44:44 | 2021-01-25T19:44:44 | 332,027,727 | 1 | 0 | null | null | null | null | UTF-8 | R | false | false | 3,889 | r | 1609874842-inps.R | list(holes = c(255L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, -16777216L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L),
numholes = integer(0), x = c(1.45106360348984e-154, 1.06914224749979e-317,
NaN, 5.05204757913007e-310, 7.29055487257632e-304, NaN, NaN,
1.29554067780721e-204, 7.06327446503934e-304, 5.56268464627306e-309,
1.35298397308854e-305, NaN, NaN, -8.63673874871551e-26, NaN,
NaN, 6.13636683162216e-92, -5.48612406879369e+303, 9.5268205270879e+139,
5.92421040714636e-304, 6.15633790123313e-304, 7.40347847110131e+172,
1.93826639428209e+228, 9.0765580786923e+223, 5.29146434604553e-310,
2.84820057756529e-304, 7.44400337317115e-15, -6.21928728136985e+199,
5.07614679289191e-315, 6.96635054780945e-310, 6.15188427514067e-304,
7.71532912545691e-320, 5.13522981413596e-312, 6.24273792049181e+144,
1.44629800802148e-307, 1.6131785474276e-307, 3.6368404566655e-307,
5.78380767624692e-180, 0, 0, -1.75633954852582e+294, 0, 0,
NaN, 7.10543077220257e-15), y = c(3.32670356219186e-310,
0, 0, 0, -5.82900682309329e+303, 7.29111854592907e-304, -2.97429758910463e+284,
-3.1599091231864e+284, 7.29111980413851e-304, NaN, 6.4757678266058e-319,
0, 0, 0, 2.17292368994844e-311, 0, 0, 0, 2.60750842793813e-310,
2.17292368995042e-311, 8.85477013632944e-310, -1.81520618710667e+280,
0, 4.26871874307727e-287, 2.17292368994844e-311, 4.73479917863508e-308,
1.20953791325285e-312, 5.32662421820014e-312, 0, 0, 0, -2.17292524414457e-311,
8.80011392415517e+223, 5.43472210425371e-322, 1.42602581544442e-105,
1.79838294486417e-307, 5.31219382408508e-320, 3.85185988877447e-34
))
testlist <- list(holes = c(255L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, -16777216L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), numholes = integer(0), x = c(1.45106360348984e-154, 1.06914224749979e-317, NaN, 5.05204757913007e-310, 7.29055487257632e-304, NaN, NaN, 1.29554067780721e-204, 7.06327446503934e-304, 5.56268464627306e-309, 1.35298397308854e-305, NaN, NaN, -8.63673874871551e-26, NaN, NaN, 6.13636683162216e-92, -5.48612406879369e+303, 9.5268205270879e+139, 5.92421040714636e-304, 6.15633790123313e-304, 7.40347847110131e+172, 1.93826639428209e+228, 9.0765580786923e+223, 5.29146434604553e-310, 2.84820057756529e-304, 7.44400337317115e-15, -6.21928728136985e+199, 5.07614679289191e-315, 6.96635054780945e-310, 6.15188427514067e-304, 7.71532912545691e-320, 5.13522981413596e-312, 6.24273792049181e+144, 1.44629800802148e-307, 1.6131785474276e-307, 3.6368404566655e-307, 5.78380767624692e-180, 0, 0, -1.75633954852582e+294, 0, 0, NaN, 7.10543077220257e-15), y = c(3.32670356219186e-310, 0, 0, 0, -5.82900682309329e+303, 7.29111854592907e-304, -2.97429758910463e+284, -3.1599091231864e+284, 7.29111980413851e-304, NaN, 6.4757678266058e-319, 0, 0, 0, 2.17292368994844e-311, 0, 0, 0, 2.60750842793813e-310, 2.17292368995042e-311, 8.85477013632944e-310, -1.81520618710667e+280, 0, 4.26871874307727e-287, 2.17292368994844e-311, 4.73479917863508e-308, 1.20953791325285e-312, 5.32662421820014e-312, 0, 0, 0, -2.17292524414457e-311, 8.80011392415517e+223, 5.43472210425371e-322, 1.42602581544442e-105, 1.79838294486417e-307, 5.31219382408508e-320, 3.85185988877447e-34 )) |
e9ea33da08eb428bf52179ad1d5014d5ee6d97dc | d1c11b61b4d7dc5c6ceee99894bc7f775280f36e | /R/estimating.R | 4e7da36f9cfabb1d2f1fa5f0eba1f5a107efb76b | [
"Apache-2.0"
] | permissive | Allisterh/natural-rates-gaps | d8a52762dc888c4aaddbd56b4018826d8f61b1ea | f184456e8a36ca31688b72a01d0f4ac30d2b0f8f | refs/heads/master | 2022-01-14T03:15:46.501689 | 2018-04-21T00:15:33 | 2018-04-21T00:15:33 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 5,485 | r | estimating.R | ## estimating
library(MCMCpack)
library(mvtnorm)
#options(digits = 10)
set.seed(1)
# Importing data
# iStart <- 1996
# iEnd <- 2017.917
# iFreq <- 12
# mY <- read.csv("data-raw/brmacrom.csv", dec=",")
# mY <- ts(mY, start = iStart, frequency = iFreq)
iP <- 12 #defasagens
iStart <- 1996
iEnd <- 2017.75
iFreq <- 4
mY <- read.csv("data-raw/brmacroq.csv", dec=",")
mY <- ts(mY, start = iStart, frequency = iFreq)
# library(seasonal)
#
# aux <- seas(x = mY[,1])
# mY[,1] <- (aux$data[,"trend"])
#
# aux <- seas(x = mY[,4])
# mY[,4] <- (aux$data[,"trend"])
mY[,1] <- log(mY[,1]/1000)
mY[,4] <- log(mY[,4])
mdY <- diff(mY)
plot(mY)
plot(mdY)
mTP <- read.csv("data-raw/brrecess.csv", dec=",")
mdY <- scale(mdY, scale = F)
cN <- ncol(mdY)
cT <- nrow(mdY)
# OLS
mx <- NULL
for (i in 1:iP) {
mx <- ts.union(mx, lag(mdY, -i))
}
ms_p <- window(mdY, iStart + 1/iFreq, iStart + iP / iFreq)
vs_p <- c(t(ms_p))
my <- window(mdY, iStart + (1/iFreq) + (iP / iFreq), iEnd)
my <- matrix(my, cT - iP, cN)
mx <- window(mx, iStart + (1/iFreq) + (iP / iFreq), iEnd)
mx <- matrix(mx, cT - iP, iP * cN)
lOLS <- ApplyOLS(my, mx)
mPhi_OLS <- lOLS$mB
mSigma_OLS <- lOLS$mS
# Empirical Bayes
lhyper <- optim(c(1, cN + 2), lnML, method = "L-BFGS-B", lower = c(.0001, cN - 1))
dLambda <- lhyper$par[1]
dN_0 <- lhyper$par[2]
#lhyper <- optimize(lnML, c(0, 100))
#dLambda <- lhyper$minimum
#dN_0 <- cN + 2
# Prior
lPrior <- SpecifyPrior(mY, iP, dLambda, dN_0)
mM_0 <- lPrior$mM_0
mD_0 <- lPrior$mD_0
dN_0 <- lPrior$dN_0
mS_0 <- lPrior$mS_0
mD_0Inv <- solve(mD_0)
# Posterior
lPosterior <- SpecifyPosterior(mM_0, mD_0, dN_0, mS_0, my, mx)
mM_1 <- lPosterior$mM_1
mD_1 <- lPosterior$mD_1
dN_1 <- lPosterior$dN_1
mS_1 <- lPosterior$mS_1
mD_1Inv <- solve(mD_1)
# Log marginal likelihood
dlnML <- ComputeLogMarginalLikelihood(mD_0, dN_0, mS_0, mD_1, dN_1, mS_1)
# Bayes factor of AR vs VAR (S-D density ratio)
dbf <- ComputeSDRatio(mD_0Inv, dN_0, mS_0, mM_1, mD_1Inv, dN_1, mS_1)
# Initial value
msigma <- riwish(dN_1, mS_1)
mphi <- DrawPhi(msigma, mM_1, mD_1Inv)
#mgamma <- ComputeInitStateVariance(mphi, msigma)
# M-H algorithm
cBurn <- 0
cR <- 10000
mphi_s <- mcmc(matrix(, cR, iP * cN ^ 2))
msigma_s <- mcmc(matrix(, cR, cN * (cN + 1) / 2))
for (r in (1 - cBurn):cR) {
# Draw parameters
msigma_star <- riwish(dN_1, mS_1)
mphi_star <- DrawPhi(msigma_star, mM_1, mD_1Inv)
# mgamma_star <- ComputeInitStateVariance(mphi_star, msigma_star)
# dalpha <- ComputePmove(mgamma, mgamma_star, vs_p)
# if (runif(1) <= dalpha) {
mphi <- mphi_star
msigma <- msigma_star
# mgamma <- mgamma_star
# }
# Save draws
if (r >= 1) {
mphi_s[r,] <- c(t(mphi))
msigma_s[r,] <- vech(msigma)
}
print(r)
}
# B-N Decomposition
amphi <- array(dim = c(cN, iP * cN, cR))
amsigma <- array(dim = c(cN, cN, cR))
for (r in 1:cR) {
amphi[,, r] <- t(matrix(mphi_s[r,], iP * cN, cN))
amsigma[,, r] <- xpnd(msigma_s[r,], cN)
}
ms <- NULL
for (i in 0:(iP - 1)) {
ms <- ts.union(ms, lag(mdY, -i))
}
ms <- window(ms, iStart + iP / iFreq, iEnd)
ms <- matrix(ms, cT - iP + 1, iP * cN)
amgap <- array(dim = c(cN, cT - iP + 1, cR))
amdgap <- array(dim = c(cN, cT - iP, cR))
amd2gap <- array(dim = c(cN, cT - iP - 1, cR))
amcorr <- array(dim = c(cN, cN, cR))
mC <- cbind(diag(cN), matrix(0, cN, (iP - 1) * cN))
for (r in 1:cR) {
ma <- GetCompanionMatrix(amphi[,, r])
mw <- -mC %*% solve(diag(iP * cN) - ma) %*% ma
amgap[,, r] <- mw %*% t(ms)
amdgap[,, r] <- t(diff(t(amgap[,, r])))
amd2gap[,, r] <- t(diff(t(amgap[,, r]), 2))
amcorr[,, r] <- cor(t(amgap[,, r]))
}
mgap_med <- t(apply(amgap, 1:2, median))
mgap_lower <- t(apply(amgap, 1:2, quantile, prob = .025))
mgap_upper <- t(apply(amgap, 1:2, quantile, prob = .975))
mgap_med <- ts(mgap_med, start = iStart + iP / iFreq, frequency = iFreq)
mgap_lower <- ts(mgap_lower, start = iStart + iP / iFreq, frequency = iFreq)
mgap_upper <- ts(mgap_upper, start = iStart + iP / iFreq, frequency = iFreq)
mY <- window(mY, iStart + iP / iFreq, iEnd)
mnr_med <- mY - mgap_med
mnr_lower <- mY - mgap_upper
mnr_upper <- mY - mgap_lower
amgapDI <- (amgap > 0)
mgapDI <- t(apply(amgapDI, 1:2, mean))
mgapDI <- ts(mgapDI, start = iStart + iP / iFreq, frequency = iFreq)
amets <- (amd2gap[, 1:(cT - iP - 3),] > 0) * (amdgap[, 2:(cT - iP - 2),] > 0) * (amgap[, 3:(cT - iP - 1),] > 0) * (amdgap[, 3:(cT - iP - 1),] < 0) * (amd2gap[, 3:(cT - iP - 1),] < 0)
amcts <- (amd2gap[, 1:(cT - iP - 3),] < 0) * (amdgap[, 2:(cT - iP - 2),] < 0) * (amgap[, 3:(cT - iP - 1),] < 0) * (amdgap[, 3:(cT - iP - 1),] > 0) * (amd2gap[, 3:(cT - iP - 1),] > 0)
mets <- t(apply(amets, 1:2, mean))
mcts <- t(apply(amcts, 1:2, mean))
mets <- ts(mets, start = iStart + iP / iFreq + .5, frequency = iFreq)
mcts <- ts(mcts, start = iStart + iP / iFreq + .5, frequency = iFreq)
# Stats
mY[, 4] <- exp(mY[, 4])
mnr_med[, 4] <- exp(mnr_med[, 4])
mnr_lower[, 4] <- exp(mnr_lower[, 4])
mnr_upper[, 4] <- exp(mnr_upper[, 4])
mgap_med[, 4] <- mY[, 4] - mnr_med[, 4];
mgap_lower[, 4] <- mY[, 4] - mnr_upper[, 4];
mgap_upper[, 4] <- mY[, 4] - mnr_lower[, 4];
save(mTP, mY, mnr_med, mgap_med, mgap_lower, mgap_upper,
amcorr, mgapDI, mets, mcts,
file = "resultados.RData")
|
0d8c108fe116d7a6d97503ffe3e584634bc31c57 | 3f4caf12ea8ddae704d573e987958b3f90fa23c0 | /EDA_case_study.R | e9ffad1f33e97113cb9062d0754064cf4094c00f | [] | no_license | harsharay/EDA-case-study | e53c2098b825202faa52de64197b4eccf2b4120e | 5ca07635a342ca0977fd43a6368ff46b9bb18c48 | refs/heads/master | 2020-04-04T19:19:02.728171 | 2018-11-05T10:41:19 | 2018-11-05T10:41:19 | 156,201,292 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 5,117 | r | EDA_case_study.R | #Create a seperate dataframe for only chargedoff status
loan_chargedOff <- loan[loan$loan_status=="Charged Off",]
View(loan_chargedOff)
#Create a seperate dataframe for only full paid loan status
loan_Paid <- loan[loan$loan_status=="Fully Paid",]
View(loan_Paid)
#Create a seperate dataframe for only current loan status
loan_current <- loan[loan$loan_status=="Current",]
View(loan_current)
#Loan amount vs loan status vs loan grades
ggplot(loan, aes(x=loan$loan_status, y=loan$loan_amnt, fill=loan$grade))+ geom_bar(stat="identity")
#Loan amount respective state and total income resepctive to state
#different statuses of loans in different states
ggplot(loan, aes(x=loan$addr_state, fill=loan$loan_status))+geom_bar()
Observations:
Highest loans are being taken from CA and lowest by IA and ID
#for charged off
ggplot(loan_chargedOff, aes(x=loan_chargedOff$addr_state, fill=loan_chargedOff$loan_status))+geom_bar()
Observations:
Highest loans charged off are from CA and the rest of the data is proportionate to total status
ggplot(loan_Paid, aes(x=loan_Paid$addr_state, fill=loan_Paid$loan_status))+geom_bar()
#graph between state and loan amount and loan status
ggplot(loan, aes(x=loan$addr_state, y=loan$loan_amnt,fill=loan$loan_status))+geom_bar(stat="identity")
#plot with state vs loan amount with annual income and status as charged off
ggplot(loan_chargedOff, aes(x=loan_chargedOff$addr_state, y=loan_chargedOff$loan_amnt, size=loan_chargedOff$annual_inc))+geom_bar(stat="identity")
#plot with state vs loan amount with annual income and status as full paid
ggplot(loan_Paid, aes(x=loan_Paid$addr_state, y=loan_Paid$loan_amnt, size=loan_Paid$annual_inc))+geom_bar(stat="identity")
#Plot for loan amount vs loan status
ggplot(loan, aes(x=loan$loan_amnt, fill=loan$loan_status))+geom_histogram(position="dodge")
#for charged off
ggplot(loan_chargedOff, aes(x=loan_chargedOff$loan_amnt))+geom_point(stat="count")
#Loan amount vs home ownership
ggplot(loan, aes(x=loan$loan_status, fill=loan$home_ownership))+geom_bar(stat="count", position="dodge")
#for charged off
ggplot(loan_chargedOff, aes(x=loan_chargedOff$loan_status, fill=loan_chargedOff$home_ownership))+geom_bar(stat="count", position="dodge")
#Observation
People who take loans with rented houses will default more
#for paid
ggplot(loan_Paid, aes(x=loan_Paid$loan_status, fill=loan_Paid$home_ownership))+geom_bar(stat="count", position="dodge")
#plot with state vs loan amount with annual income and status as charged off
ggplot(loan_chargedOff, aes(x=loan_chargedOff$addr_state, y=loan_chargedOff$loan_amnt, col=loan_chargedOff$loan_status))+geom_point()
#Loan status vs annual income
ggplot(loan, aes(y=loan$annual_inc, x= loan$loan_status, col= loan$loan_status))+geom_point()
#charged off
ggplot(loan_chargedOff, aes(y=loan_chargedOff$annual_inc, x= loan_chargedOff$loan_status, col= loan_chargedOff$loan_status))+geom_point()
Observation:
Induviduals with annual income between 0 and 400000 are more in number for defaulting
#paid
ggplot(loan_Paid, aes(y=loan_Paid$annual_inc, x= loan_Paid$loan_status, col= loan_Paid$loan_status))+geom_point()
#Loan status vs late fee
ggplot(loan, aes(x=loan$loan_status, y=loan$total_rec_late_fee, fill=loan$loan_status))+geom_bar(stat="identity")
#7.stats in grades
#for all the loans
ggplot(loan, aes(x=loan$grade, fill=loan$loan_status))+geom_bar()
#for charged off loans
ggplot(loan_chargedOff, aes(x=loan_chargedOff$grade, fill=loan_chargedOff$grade))+geom_bar()
#Observation:
grades B, C loans have high chance of getting defaulted
#for paid loans
ggplot(loan_Paid, aes(x=loan_Paid$grade, fill=loan_Paid$grade))+geom_bar()
#for current loans
ggplot(loan_current, aes(x=loan_current$grade))+geom_bar()
#Intrest rates among different loan status
ggplot(loan, aes(fill=loan$loan_status, x=loan$int_rate))+geom_histogram(position="dodge")
#Fully Pad loan
ggplot(loan_Paid, aes(x=loan_Paid$int_rate))+geom_bar()
#charged off loan
ggplot(loan_chargedOff, aes(x=loan_chargedOff$int_rate))+geom_bar()
#Observation
Loans with intr. rate between 12 to 15 have high chance of getting defaulted
#Term vs loan status
ggplot(loan,aes(fill=loan$loan_status, x=loan$term))+geom_histogram(position="dodge")
#chargedoff
ggplot(loan_chargedOff,aes(fill=loan_chargedOff$loan_status, x=loan_chargedOff$term))+geom_histogram()
#paid
ggplot(loan_Paid,aes(fill=loan_Paid$loan_status, x=loan_Paid$term))+geom_histogram()
#Aggregate values for number of loans charged off
#per state
loan$charged_off <- ifelse(loan1$loan_status=="Charged Off",1,0)
aggregate(loan$charged_off~loan$addr_state, FUN=sum)
#per grade
aggregate(loan1$charged_off~loan1$grade, FUN=sum)
#EXTRA
ggplot(loan, aes(x=loan$loan_status, y=loan$loan_amnt, col=loan$grade, size=loan$int_rate, shape=loan$home_ownership))+ geom_point(stat="identity")
ggplot(loan, aes(size=loan$loan_status, x=loan$loan_amnt, col=loan$grade, y=loan$int_rate, shape=loan$home_ownership))+ geom_point(stat="identity")
|
edecf92a5a5c12c272792bdbbee47ff015509bdc | 4ca3723018b7998478095b402ddc9a1cbeb2aa33 | /run_analysis.R | 9e4202ba68d09831549c2d55ee8ab814c9e215b1 | [] | no_license | dscoursera/datacleaning | d65198b922c5adcd140886d2fdd588b16ea349fe | 98cf1dd183c142696f3421a94a388cb127125369 | refs/heads/master | 2021-01-21T06:59:14.768460 | 2014-06-20T17:03:16 | 2014-06-20T17:03:16 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 2,756 | r | run_analysis.R | ## preliminaries ##
fileUrl <- "https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip"
if (!file.exists("UCI HAR Dataset.zip")) download.file(fileUrl, destfile="./UCI HAR Dataset.zip", method = "curl")
dateDownloaded <- date()
dateDownloaded
require(reshape2, quietly = TRUE)
#
## unzip the data folder in working dir
unzip("UCI HAR Dataset.zip")
#
## read in test data sets
testXvalues <- read.table("UCI HAR Dataset/test/X_test.txt", comment.char = "", colClasses="numeric")
testYvalues <- read.table("UCI HAR Dataset/test/y_test.txt", comment.char = "", colClasses="factor")
testSvalues <- read.table("UCI HAR Dataset/test/subject_test.txt", comment.char = "", colClasses="numeric")
#
## read in train data sets
trainXvalues <- read.table("UCI HAR Dataset/train/X_train.txt", comment.char = "", colClasses="numeric")
trainYvalues <- read.table("UCI HAR Dataset/train/y_train.txt", comment.char = "", colClasses="factor")
trainSvalues <- read.table("UCI HAR Dataset/train/subject_train.txt", comment.char = "", colClasses="numeric")
#
## read in features and activity labels
features <- read.table("UCI HAR Dataset/features.txt", comment.char = "", colClasses="character")
alabels <- read.table("UCI HAR Dataset/activity_labels.txt", comment.char = "")
#
## combine the columns of test data sets and rename columns
dftest <- cbind(testXvalues, testYvalues, testSvalues)
names(dftest) <- c(features$V2, "activity", "subjectid")
#
## combine the columns of train data sets
dftrain <- cbind(trainXvalues, trainYvalues, trainSvalues)
names(dftrain) <- c(features$V2, "activity", "subjectid")
#
## combine the train and test data sets (dfcomb)
dfcomb <- rbind(dftrain, dftest)
#
### subset ###
## keep only the columns of measurements on the mean() and std()
## first remove the columns with meanFreq():derived col, not measured col
grf <- grep("-meanFreq()", names(dfcomb))
dfcomb2 <- dfcomb[, -c(grf)]
## keep mean() and std() columns plus the last two columns
grm <- grep("-mean()", names(dfcomb2))
grs <- grep("-std", names(dfcomb2))
dfcomb2 <- dfcomb2[, c(grm,grs,549,550)]
#
## convert activity numbers to names using the second column in alabels table
levels(dfcomb2$activity) <- alabels$V2
#
## ## make descriptive variable names
names(dfcomb2) <- gsub("\\(\\)", "", names(dfcomb2))
names(dfcomb2) <- gsub("-", "", names(dfcomb2))
#
## tidy data set
pjmelt <- melt(dfcomb2,id=c("activity","subjectid"), measure.vars=c(1:66))
tidydata <- dcast(pjmelt, subjectid + activity ~ variable, mean)
# 180 rows, 68 columns
write.table(tidydata, file = "tidydata.txt", sep = "\t", row.names = FALSE, col.names = TRUE)
|
ebb7206ed02d0fca31f61fa805f5f139fba473c2 | 161747aed56bfc7fbd17b87c60c25291ef12a579 | /data_exploration.R | aa9347d28e4bfac5394c7b10a43d5a55df749216 | [] | no_license | juschu321/CRAN_meta | 62f3dc210eecd1684c2cb4d11531ff0bdcfca65f | 333375a95cd6606e16fc06b0c03b78516fc090ed | refs/heads/master | 2020-06-02T22:43:02.452187 | 2019-07-16T15:40:55 | 2019-07-16T15:40:55 | 191,332,470 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,962 | r | data_exploration.R | library(readr)
install.packages("tidyr")
library(tidyr)
library(cranlogs)
library(dplyr)
library(ggplot2)
read.csv("mydata.csv")
#Datum formatieren
my_data <- read_csv("mydata.csv", col_types = cols(date = col_date(format = "%Y-%m-%d")))
View(my_data)
#check the data structure
str(my_data)
#my_data zu data_frame umgewandelt
data_frame <- as.data.frame(my_data)
my_data_spread <- tidyr::spread(data=my_data, key = package, value = count)
View(my_data_spread)
#Tage zu Monate aggregiert
monthly <-
my_data %>%
mutate(day = format( date, "%d"), month = format(date, "%m"),
year = format(date, "%Y")) %>%
group_by(year, month, package) %>%
summarise(total = sum(count))
monthly_df <-as.data.frame(monthly)
monthly_spread <- tidyr::spread(monthly_df, key = package, value = total)
####ggplot playground####
ggplot(data=my_data_spread, aes(x=date))+
geom_point(aes(y=AnalyzeFMRI), color='red') +
geom_point(aes(y=aspect), color='blue') +
labs(x = "date", y = "count")
ggplot(data=my_data_spread, aes(x=date))+
geom_line(aes(y=AnalyzeFMRI), color='green') +
geom_line(aes(y=aspect), color = 'blue')+
geom_line(aes(y=asymmetry), color = 'red')+
labs(x= "date", y = "count")
View(my_data)
plot <- ggplot(data = my_data, mapping = aes(x = count, y = package)) +
geom_point(alpha = 0.1, color = "blue")+
labs(x= "count", y = "package")
plot
#ade4a <- my_data_spread%>%
#select(date,ade4)
#visualization of the distribution of package ade4
#ggplot (data = ade4a)+
# geom_point(aes(date,ade4a), position = "identity",
# pch =21, fill = "steelblue", alpha = 1/4, size = 2)+
# labs(title = "Distribution of downloads of the package ade4",
# x = "date", y = "count")
#visualization of two different packages
#ggplot (data = my_data_spread, aes (x = date))+
# geom_line(aes(y=ade4), color='red') +
# geom_line(aes(y=betareg), color='blue') +
# labs(x = "date", y = "count")
|
456f2ae408cf618e95968a270e645861dc33afe0 | 235bac0fcef5acd7a8d2fc1e95cec355efeaa4aa | /REGRESSION/regresion_boosting_fun.R | e051844d752905c85c77fb253cef4bac50bf6d20 | [] | no_license | haachicanoy/RAW_REGRESSION_MODELS_BIGDATA | 4a139c1346b75f7b1e1f04bfa58e37ef024af266 | 13457bab7aa6e0e2020e872ebe2695102a19bb0e | refs/heads/master | 2020-12-11T03:26:06.298543 | 2016-11-04T00:34:02 | 2016-11-04T00:34:02 | 47,995,776 | 2 | 0 | null | 2015-12-14T19:14:23 | 2015-12-14T19:14:22 | null | UTF-8 | R | false | false | 9,602 | r | regresion_boosting_fun.R | ## All subsequent models are then run in parallel
boostingFun <- function(variety,dirLocation=paste0(getwd(),"/"),barplot=FALSE,
col.grap="lightskyblue",nb.it = 100,saveWS=F,wid=500,
hei=800,ab=7,iz=4.1,ar=4.1,de=2.1,ncores=21,sztxty=15,
sztxtx=15,szlbty=15,szlbtx=15,szmain=15,pp.szmain=15,
pp.sztxtx=15,pp.sztxty=15,pp.szlbty=18,pp.szlbtx=18,
pp.lgndtx=15)
{
ngw <- nchar(dirLocation)
if( substring(dirLocation,ngw-16,ngw)=="VARIETY_ANALYSIS/" ){}else{return(cat("Aun no se encuentra en la carpeta VARIETY_ANALYSIS\nUtilize la funcion setwd para dirigirse a este carpeta"))}
Sys.time()->start
require(party)
require(caret)
require(snowfall)
require(reshape)
require(stringr)
require(agricolae)
require(gbm)
require(plyr)
sfInit(parallel=T,cpus=ncores)
sfLibrary(caret)
sfLibrary(gbm)
sfLibrary(plyr)
dirDataSet <- paste0(dirLocation,variety,"/DATA_SETS/",variety,"_complet.csv")
dirSave <- paste0(dirLocation,variety,"/STOC_GRAD_BOOS/")
dataSets <- lapply(dirDataSet,function(x){read.csv(x,row.names=1)})
cat(paste("gbm with Conditional Importance:\n"))
boostingCaret <- function(x)
{
setseed <- .Random.seed[1:nb.it]
nOutPut <- ncol(data)
# pb <- winProgressBar(title="Progress bar", label="0% done", min=0, max=100, initial=0)
# info <- sprintf("%d%% done", round((i/(nb.it)*100)))
# setWinProgressBar(pb, paste(i/(nb.it)*100), label=info)
inTrain <- createDataPartition(y=data[,nOutPut], p=0.7, list=F)
training <- data[inTrain,]
testing <- data[-inTrain,]
grid <- expand.grid(interaction.depth = c(1, 5, 9),
n.trees = (14:30)*50,
shrinkage = c(0.001,0.01,0.1),
n.minobsinnode = c(5,10,20))
fitControl <- trainControl(## 10-fold CV
method = "repeatedcv",
number = 10,
## repeated ten times
repeats = 10)
Sys.time()->start
model <- train(training[,-ncol(training)], training[,ncol(training)],
method="gbm", tuneGrid=grid,bag.fraction = 0.8)
print(Sys.time()-start)
performance <- R2(predict(model, testing), testing[,nOutPut]) * 100
vaRelevance <- varImp(model, scale=F, conditional=T)$importance
return(list(model,performance,vaRelevance))
}
# close(pb)
sfExport("boostingCaret")
sfExport("nb.it")
for(j in 1:length(variety))
{
cat(paste(j,"- Variety:",variety[j],"\n"))
data0 <- dataSets[[j]]
nvz <- nearZeroVar(data0)
if(length(nvz)==0){data <- data0}else{data <- data0[,-nvz] }
v <- integer()
sfExport("data")
cat(paste("Running ",nb.it,"models in cross validation\n"))
boostingModels <- sfLapply(1:nb.it,boostingCaret)
allModels <- lapply(boostingModels,function(x){x[[1]]})
#allRMSE <- unlist(lapply(allModelsAndRMSE,function(x){x[[2]]}))
performance <- unlist(lapply(boostingModels,function(x){x[[2]]}))
relevances <- lapply(boostingModels,function(x){x[[3]]})
bestMod <- allModels[which(performance==max(performance))][[1]]
write.table(bestMod$bestTune,paste(dirSave[j],"best_model.txt"),sep="\t")
currentVarImp <- do.call(cbind,relevances)
#sort(apply(do.call(cbind,currentVarImp),1,mean),decreasing = T)
scale <- performance / as.numeric(apply(currentVarImp,2,sum))
scaledVarImp <- t(t(currentVarImp) * scale)
ord <- list(0) ; for(k in 1:ncol(scaledVarImp)){ord[[k]] <- scaledVarImp[,k]}
ordered <- lapply(ord,function(x){sort(x,decreasing = T)})
princVar <- lapply(ordered,function(x){names(x)[1:3]})
cat(paste("Computing profiles\n"))
#profilesList <- sfLapply(1:100,function(x){ profLis <- list(0,0,0);names(profLis) <- princVar[[x]] ;for(n in princVar[[x]]){ profil <- profilePlot(allModels[[x]], n, data, F) ; profLis[[n]] <- data.frame(profil$y) ; row.names(profLis[[n]]) <- profil$x };return(profLis)})
profilesList <- lapply(1:nb.it,function(x){ profLis <- list(0,0,0);names(profLis) <- princVar[[x]] ;for(n in princVar[[x]]){ profil <- profilePlot(allModels[[x]], n, data, F) ; profLis[[n]] <- data.frame(profil$y) ; row.names(profLis[[n]]) <- profil$x };return(profLis)})
profiles <- list()
length(profiles) <- length(names(data)[-ncol(data)])
names(profiles) <- names(data)[-ncol(data)]
for(z in 1:length(ordered))
{
toProfile <- profilesList[[z]]
for(n in names(toProfile)) {
profile <- toProfile[n]
if(length(profiles[[n]]) == 0) {
profiles[[n]] <- as.data.frame(profile)
#names(profiles)[n] <- n
#row.names(profiles[[n]]) <- profile$x
} else {
profiles[[n]] <- cbind(profiles[[n]],as.data.frame(profile))
}
}
}
v <- as.data.frame(scaledVarImp)
write.csv(v,paste0(dirSave[j],"weighMatrix.csv"))
perf1 <- signif(sum(performance) / nb.it, 5)
if(barplot){
#Comienzo de barPlot
se <- apply(v, 1, function(x){ 1.96*sd(x, na.rm=TRUE)/sqrt(ncol(v))})
se <- data.frame(se,names(se))
names(se) <- c("se","Variable")
ordered <- sort(apply(v,1, median), decreasing=F)
mean <- as.data.frame(ordered)
mean <- cbind(mean, names(ordered))
names(mean) <- c("Mean", "Variable")
mean$Variable <- factor(names(ordered), levels= names(ordered))
stadistc <- merge(se,mean,by.x="Variable",by.y="Variable")
stadistc <- stadistc[order(stadistc$Mean,decreasing=F),]
errBars <- transform(stadistc, lower=Mean-se,upper=Mean+se )
png(paste0(dirSave[j],"InputRelvance.png"),width = wid, hei = hei, pointsize = 20)
m <- ggplot(mean, aes(x=Variable, y=Mean))
m <- m + geom_bar(stat="identity", width=0.5, fill="slategray1") + ylab("Mean importance")+
geom_errorbar(aes(ymax = lower, ymin=upper), width=0.25,data=errBars) + coord_flip() +
theme_bw() +
ggtitle(paste("Importance of variables (with a mean R2 of", perf1, "%)")) +
theme(plot.title = element_text(size = szmain,
face = "bold", colour = "black", vjust = 1.5),
axis.text.y =element_text(size = sztxty),
axis.text.x =element_text(size = sztxtx),
axis.title.x = element_text(size = szlbty),
axis.title.y = element_text(size = szlbtx))
suppressWarnings(print(m))
dev.off()
}else{
#Comienzo boxplot
require(cowplot)
newV <- melt(t(v))[,-1]
names(newV) <- c("variable","value")
medOrdenada <- names(with(newV,sort(tapply(value,variable,median))))
newV$variable <- factor(newV$variable,levels=medOrdenada)
noParameOut <- kruskal(newV$value,newV$variable,group = T)
groupsData <- data.frame(noParameOut$groups$trt,noParameOut$groups$M)
groupsData$noParameOut.groups.trt <- str_replace_all(groupsData$noParameOut.groups.trt, pattern=" ", repl="")
maxDist <- {maxDis <- tapply(newV$value,newV$variable,max)+4.5;data.frame(nam=names(maxDis),max=maxDis)}
groupsData <- merge(groupsData,maxDist,by.x="noParameOut.groups.trt",by.y="nam",all=T,sort=F)
newV1 <- merge(newV,groupsData,by.x="variable",by.y="noParameOut.groups.trt",all.x=T,all.y=F,sort = F)
png(paste0(dirSave[j],"InputRelvance.png"),width = wid, hei = hei, pointsize = 20)
m <- ggplot(newV1, aes(x=variable, y=value))
m <- m + geom_boxplot(fill=col.grap) + ylab("Importance")+ xlab("Input variable")+
theme_bw() +
ggtitle(paste("Importance of variables (with a mean R2 of", perf1, "%)")) +
theme(axis.text.x = element_text(angle=0, hjust=0.5,
vjust=0,size=sztxtx),plot.title = element_text(vjust=3,size=szmain),
axis.text.y =element_text(size = sztxty),
axis.title.x = element_text(size = szlbty),
axis.title.y = element_text(size = szlbtx))+ coord_flip()+
geom_text(aes(y = max,label = noParameOut.groups.M))
print(ggdraw(switch_axis_position(m, 'x')))
dev.off()
}
#Fin del grafico boxplot
namSort <- names(sort(apply(v,1, median), decreasing=T))
profData <- unlist(lapply(profiles,function(x){!is.null(x)}))
profRealData <- names(profData)[profData]
limProf <- if(length(profRealData) < 5){ length(profRealData)}else{5}
for(i in 1:limProf)
{
if(!is.null(unlist(profiles[namSort[i]])))
{
png(paste0(dirSave[j],"MultiProfile_",namSort[i],".png"),width =,650, hei =410 , pointsize = 40)
multiProfile(data,profiles,namSort[i],pp.szmain=pp.szmain,
pp.sztxtx=pp.sztxtx,pp.sztxty=pp.sztxty,
pp.szlbty=pp.szlbty,pp.szlbtx=pp.szlbtx,
pp.lgndtx=pp.lgndtx)
dev.off()
} else{print(paste("Few profiles references for:",namSort[i]))}
}
if(saveWS==T){save(list = ls(all = TRUE), file = paste0(dirSave[j],"workSpace.RData"))}else{}
}
sfStop()
print(Sys.time()-start)
} |
566c92db4b8e45e8c7177e07b0b93c48562f73db | d157188fced5eb338f3c5adc4007e29ddf7c299d | /R/factorAxis.R | f89082b218e78c5325a770375ac1f78990a1e4b8 | [] | no_license | oldi/visreg | cefe7e80f57f1181da163d99af848eb0c48d8f4b | 418731d8b735cd4e5e6d226725c8cc5c45e3700d | refs/heads/master | 2021-01-23T16:41:25.967320 | 2015-04-21T21:34:34 | 2015-04-21T21:34:34 | 43,887,431 | 1 | 0 | null | 2015-10-08T12:40:23 | 2015-10-08T12:40:23 | null | UTF-8 | R | false | false | 393 | r | factorAxis.R | factorAxis <- function(xx, w, nn) {
l <- levels(xx)
K <- length(levels(xx))
len <- K*(1-w)+(K-1)*w
m <- ((0:(K-1))/len+(1-w)/(2*len))
ind <- numeric(nn)
for(k in 1:K) {
i1 <- ceiling(nn*(k-1)/len)
i2 <- ceiling(nn*((k-1)/len + (1-w)/len))
i3 <- ceiling(nn*k/len)
ind[i1:i2] <- k
if (k!=K) ind[(i2+1):i3] <- NA
}
list(x=seq(0,1,length=nn),m=m,l=l,ind=ind)
}
|
b5293ed1541613f957f26f3dc410dc87004a6144 | d5d69987f91a8ce7e67f3a0d21c13eb6a7c14e3b | /AccGenSVM/AccGenSVM/scripts/notransfer.R | e89f1300ad8fd45df40be68b2b0b2f28109e2399 | [] | no_license | dianabenavidesp/PhDProject | 73c4ada14f3050cd043b4d98054f7c8bbace634d | 086d460aaba591381bf0d97a748148958d6bb5d3 | refs/heads/master | 2022-09-27T01:30:30.795291 | 2020-05-07T06:48:25 | 2020-05-07T06:48:25 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 3,053 | r | notransfer.R | existsFilePredict<-function(wd, dataRep, percentData, positive, negative)
{
if(file.exists(paste(wd,"/positives/",positive,"/",percentData*100,"percent/data/data",dataRep,"/sampletest",positive,"_",negative,".csv.scale",sep=""))
&& file.size(paste(wd,"/positives/",positive,"/",percentData*100,"percent/data/data",dataRep,"/sampletest",positive,"_",negative,".csv.scale",sep="")) > 0)
{
return(1)
}
else
{
return(0)
}
}
existsModelRelated<-function(wd, dataRep, percentData, related, negative)
{
if(file.exists(paste(wd,"/related/",related,"/",percentData*100,"percent/training/data",dataRep,"/samplebase",related,"_",negative,".csv.model",sep=""))
&& file.size(paste(wd,"/related/",related,"/",percentData*100,"percent/training/data",dataRep,"/samplebase",related,"_",negative,".csv.model",sep="")) > 1100)
{
return(1)
}
else
{
return(0)
}
}
notransfer1<-function(class, relatedAll, percentData, percentHyp)
{
setwd("C:/Users/dben652/workspace/AccGenSVM/data/imagenet2/")
general<-"java -jar libsvmpredict.jar "
instructions<-as.character()
maxHyps<-256*percentHyp
numHyps<-0
for(dataRep in 1:30)
{
for(i in 1:256)
{
negative<-i
numHyps<-0
for(j in 1:256)
{
negativeRelated <- j
for(rel in 1:length(relatedAll))
{
related <- relatedAll[rel]
if(numHyps<= maxHyps && existsFilePredict(getwd(), dataRep, percentData, class, negative) == 1 && existsModelRelated(getwd(), dataRep, percentData, related, negativeRelated) == 1)
{
instructions1<-paste(general, getwd(),"/positives/",class,"/",percentData*100,"percent/data/data",dataRep,"/sampletest",class,"_",negative,".csv.scale ", sep="")
instructions2<-paste(getwd(),"/related/",related,"/",percentData*100,"percent/training/data",dataRep,"/samplebase",related,"_",negativeRelated,".csv.model ", sep="")
instructions3<-paste(getwd(),"/positives/",class,"/",percentData*100,"percent/testbase/data",dataRep,"/sampletest",class,"_",negative,"usingbase_",related,"_",negativeRelated,"_",percentHyp*100,"hyp.txt ", sep="")
instructions4<-paste(">> ",getwd(),"/positives/",class,"/",percentData*100,"percent/testbase/data",dataRep,"/sampletest",class,"_",negative,"usingbase_",related,"_",negativeRelated,"_",percentHyp*100,"hyp.out ", sep="")
instructions<-paste(instructions1, instructions2, instructions3, instructions4,sep="")
write.table(instructions, file=paste("C:/Users/dben652/workspace/AccGenSVM/HTL/scripts/testnotransfer",class,"-",percentData*100,"data.sl",sep=""), append=TRUE, col.names = FALSE, row.names = FALSE, quote = FALSE)
numHyps<-numHyps + 1
}
}
}
}
}
}
notransfer1(251,c(243, 248),0.1, 0.10)
notransfer1(43,c(12, 74),0.1, 0.10)
notransfer1(35,c(78, 100),0.1, 0.10) |
b44341a19db7c95d309e3acaa90f596b501b4177 | ad921a92fe29537d7cbf7045ddeff28b98a5ddfd | /Algorithms/Bisection Method.R | c4256aad67183334535ac79ad98ea845e225ea47 | [
"MIT"
] | permissive | nusretipek/NumericalAnalysisR | c321a3dcaeb6f613667fa0f924461e8874f59719 | ac1b2a05fc7ecb69579fa496e8afca4589879b07 | refs/heads/master | 2023-02-06T11:20:35.528258 | 2020-12-29T21:11:25 | 2020-12-29T21:11:25 | 325,373,061 | 3 | 0 | null | 2020-12-29T20:32:19 | 2020-12-29T19:44:06 | R | UTF-8 | R | false | false | 1,435 | r | Bisection Method.R | ##################################################################################
# Edit Following Function/Parameters
##################################################################################
rm(list = ls())
#Options
options(scipen = 999)
options(digits =10)
#Function
f1 <- quote(x^3 - 2*x^2 - 5)
#Parameters
lower <- 2
upper <- 4
maxiteration <- 20
##################################################################################
# WARNING: Editing the following code may reuslt with crash! Use caution
##################################################################################
#Set Environment
f1_a = eval(f1, list(x=lower))
f1_b = eval(f1, list(x=upper))
results <- data.frame(Iteration = numeric(maxiteration), x_a = numeric(maxiteration), x_b = numeric(maxiteration), x_m = numeric(maxiteration),
fx_a = numeric(maxiteration), fx_b = numeric(maxiteration), fx_c = numeric(maxiteration))
#Compute
{
if(f1_a*f1_b > 0){
print("There is no root in the range!")}
else{
for(i in 1:maxiteration){
midpoint <- (lower + upper)/2
f1_a = eval(f1, list(x=lower))
f1_b = eval(f1, list(x=upper))
f1_c = eval(f1, list(x=midpoint))
results[i,] <- list(i, lower, upper, midpoint, f1_a, f1_b, f1_c)
if(f1_a*f1_c < 0){
upper = midpoint
}
else{
lower = midpoint
}
}
}}
print(results)
|
82884a33004c5181cf52c3f6b544d30b5516cd31 | 2b8569d206b99a3c3b48b8ed7c70d48aabc1a821 | /man/get_filestream_path.Rd | c8e7186674721cdd2659dc8dba0cd2ed5a209ae0 | [
"MIT"
] | permissive | emlab-ucsb/startR | 29190d9f24a05e6c6316e1f0e88b3d6cf1149111 | 49d5c9acd531320671d7ae411231fa0cfc15c557 | refs/heads/master | 2023-08-11T23:09:22.035471 | 2021-10-08T18:07:22 | 2021-10-08T18:07:22 | 141,326,123 | 1 | 1 | MIT | 2021-10-08T18:07:16 | 2018-07-17T18:07:28 | R | UTF-8 | R | false | true | 397 | rd | get_filestream_path.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/get_filestream_path.R
\name{get_filestream_path}
\alias{get_filestream_path}
\title{Get Filestream path}
\usage{
get_filestream_path()
}
\value{
The OS-specific mounting of FIleStream
}
\description{
Identifies the operative system in which we are running, and returns the correct path to where Filestream is mounted
}
|
5c03539f993d0a6a455d131958e748822c157678 | 451bc23c13bf5e4ea6894c5c388122396cb2266f | /15-Lessons/1-Recommended/Activities/07-Ins_Tidyverse/Solved/Tidyverse.R | bf14f548917a326c328afd2ac792ae0ed4353e6d | [] | no_license | junepwk/UCF-VIRT-DATA-PT-04-2021-U-B | 92f54f5a13a9b48eec6e8ceca978bfa563ca6c39 | 30494d208a4af0ad6259056ffbf1c5f0009eb404 | refs/heads/main | 2023-07-17T23:21:33.939288 | 2021-09-02T00:55:08 | 2021-09-02T00:55:08 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,083 | r | Tidyverse.R | # Import Tidyverse
library(tidyverse)
# Use the pipe operator with mutate to create a new calcualted field
zillow_oc_2017 <- zillow_oc_2017 %>% mutate(acres=lotsizesquarefeet/43560)
# Use the pipe operator with group_by to summarize and return the count of records by category
grouped_by_zip <- zillow_oc_2017 %>% group_by(regionidzip) %>% summarize(Count=n(), .groups="keep")
grouped_by_year <- zillow_oc_2017 %>% group_by(yearbuilt) %>% summarize(Count=n(), .groups="keep")
# Use the pipe operator with group_by to summarize and return summary statistics on multiple fieds
grouped_by_year <- zillow_oc_2017 %>% group_by(yearbuilt) %>% summarize(Count=n(),
Mean_SqFt=mean(finishedsquarefeet),
Median_SqFt=median(finishedsquarefeet),
Max_Tax_Value=max(taxvaluedollarcnt),
.groups="keep") |
8d1ef6316abff0b5118e8c2d94984d076b9534bf | ce8d13de6aa47617809c5fc4d83ccd961b310104 | /man/lgbm.cv.prep.Rd | 9efcea56f74e9fb661f24d394259d0dc1f8e3c16 | [] | no_license | BruceZhaoR/Laurae | 2c701c1ac4812406f09b50e1d80dd33a3ff35327 | 460ae3ad637f53fbde6d87b7b9b04ac05719a169 | refs/heads/master | 2021-01-22T12:24:50.084103 | 2017-03-24T19:35:47 | 2017-03-24T19:35:47 | 92,722,642 | 0 | 1 | null | 2017-05-29T08:51:26 | 2017-05-29T08:51:26 | null | UTF-8 | R | false | true | 6,219 | rd | lgbm.cv.prep.Rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/lgbm.cv.prep.R
\name{lgbm.cv.prep}
\alias{lgbm.cv.prep}
\title{LightGBM Cross-Validated Model Preparation}
\usage{
lgbm.cv.prep(y_train, x_train, x_test = NA, SVMLight = is(x_train,
"dgCMatrix"), data_has_label = FALSE, NA_value = "nan",
workingdir = getwd(), train_all = FALSE, test_all = FALSE,
cv_all = TRUE, train_name = paste0("lgbm_train", ifelse(SVMLight, ".svm",
".csv")), val_name = paste0("lgbm_val", ifelse(SVMLight, ".svm", ".csv")),
test_name = paste0("lgbm_test", ifelse(SVMLight, ".svm", ".csv")),
verbose = TRUE, folds = 5, folds_weight = NA, stratified = TRUE,
fold_seed = 0, fold_cleaning = 50)
}
\arguments{
\item{y_train}{Type: vector. The training labels.}
\item{x_train}{Type: data.table or dgCMatrix (with \code{SVMLight = TRUE}). The training features.}
\item{x_test}{Type: data.table or dgCMatrix (with \code{SVMLight = TRUE}). The testing features, if necessary. Not providing a data.frame or a matrix results in at least 3x memory usage. Defaults to \code{NA}.}
\item{SVMLight}{Type: boolean. Whether the input is a dgCMatrix to be output to SVMLight format. Setting this to \code{TRUE} enforces you must provide labels separately (in \code{y_train}) and headers will be ignored. This is default behavior of SVMLight format. Defaults to \code{FALSE}.}
\item{data_has_label}{Type: boolean. Whether the data has labels or not. Do not modify this. Defaults to \code{FALSE}.}
\item{NA_value}{Type: numeric or character. What value replaces NAs. Use \code{"na"} if you want to specify "missing". It is not recommended to use something else, even by soemthing like a numeric value out of bounds (like \code{-999} if all your values are greater than \code{-999}). You should change from the default \code{"na"} if they have a real numeric meaning. Defaults to \code{"na"}.}
\item{workingdir}{Type: character. The working directory used for LightGBM. Defaults to \code{getwd()}.}
\item{train_all}{Type: boolean. Whether the full train data should be exported to the requested format for usage with \code{lgbm.train}. Defaults to \code{FALSE}.}
\item{test_all}{Type: boolean. Whether the full test data should be exported to the requested format for usage with \code{lgbm.train}. Defaults to \code{FALSE}.}
\item{cv_all}{Type: boolean. Whether the full cross-validation data should be exported to the requested format for usage with \code{lgbm.cv}. Defaults to \code{TRUE}.}
\item{train_name}{Type: character. The name of the default training data file for the model. Defaults to \code{paste0('lgbm_train', ifelse(SVMLight, '.svm', '.csv'))}.}
\item{val_name}{Type: character. The name of the default validation data file for the model. Defaults to \code{paste0('lgbm_val', ifelse(SVMLight, '.svm', '.csv'))}.}
\item{test_name}{Type: character. The name of the testing data file for the model. Defaults to \code{paste0('lgbm_test', ifelse(SVMLight, '.svm', '.csv'))}.}
\item{verbose}{Type: boolean. Whether \code{fwrite} data is output. Defaults to \code{TRUE}.}
\item{folds}{Type: integer, vector of two integers, vector of integers, or list. If a integer is supplied, performs a \code{folds}-fold cross-validation. If a vector of two integers is supplied, performs a \code{folds[1]}-fold cross-validation repeated \code{folds[2]} times. If a vector of integers (larger than 2) was provided, each integer value should refer to the fold, of the same length of the training data. Otherwise (if a list was provided), each element of the list must refer to a fold and they will be treated sequentially. Defaults to \code{5}.}
\item{folds_weight}{Type: vector of numerics. The weights assigned to each fold. If no weight is supplied (\code{NA}), the weights are automatically set to \code{rep(1/length(folds))} for an average (does not mix well with folds with different sizes). When the folds are automatically created by supplying \code{fold} a vector of two integers, then the weights are automatically computed. Defaults to \code{NA}.}
\item{stratified}{Type: boolean. Whether the folds should be stratified (keep the same label proportions) or not. Defaults to \code{TRUE}.}
\item{fold_seed}{Type: integer or vector of integers. The seed for the random number generator. If a vector of integer is provided, its length should be at least longer than \code{n}. Otherwise (if an integer is supplied), it starts each fold with the provided seed, and adds 1 to the seed for every repeat. Defaults to \code{0}.}
\item{fold_cleaning}{Type: integer. When using cross-validation, data must be subsampled. This parameter controls how aggressive RAM usage should be against speed. The lower this value, the more aggressive the method to keep memory usage as low as possible. Defaults to \code{50}.}
}
\value{
The \code{folds} and \code{folds_weight} elements in a list if \code{cv_all = TRUE}. All files are output and ready to use for \code{lgbm.cv} with \code{files_exist = TRUE}. If using \code{train_all}, it is ready to be used with \code{lgbm.train} and \code{files_exist = TRUE}. Returns \code{"Success"} if \code{cv_all = FALSE} and the code does not error mid-way.
}
\description{
This function allows you to prepare the cross-validatation of a LightGBM model.
It is recommended to have your x_train and x_val sets as data.table (or data.frame), and the data.table development version. To install data.table development version, please run in your R console: \code{install.packages("data.table", type = "source", repos = "http://Rdatatable.github.io/data.table")}.
SVMLight conversion requires Laurae's sparsity package, which can be installed using \code{devtools:::install_github("Laurae2/sparsity")}. SVMLight format extension used is \code{.svm}.
Does not handle weights or groups.
}
\examples{
\dontrun{
Prepare files for cross-validation.
trained.cv <- lgbm.cv(y_train = targets,
x_train = data[1:1500, ],
workingdir = file.path(getwd(), "temp"),
train_conf = 'lgbm_train.conf',
train_name = 'lgbm_train.csv',
val_name = 'lgbm_val.csv',
folds = 3)
}
}
|
197e90d33c947cfbca92ec5dca21fdaf181be541 | cf2e6e452e1885e870c7ab2e1565d22b0cc31841 | /AnalysisScript.R | 9b6ac1c64da210b8a35b1b569dd70da4d894f564 | [] | no_license | linleyj/KateLindyMaryamTestRepo | 3165be0d20feaa1eeb333602ffbe4ea2bf7a00bf | 81ea89726db26f93b7594f9b1cef72bdfdfae543 | refs/heads/master | 2021-04-15T08:23:09.906358 | 2018-03-22T23:17:03 | 2018-03-22T23:17:03 | 126,405,946 | 0 | 0 | null | 2018-03-22T23:17:20 | 2018-03-22T23:17:20 | null | UTF-8 | R | false | false | 48 | r | AnalysisScript.R | library(tidyverse)
library(lme4)
library(plotly) |
00a0fc9de3222de4c1c4974d1fde341cf4d26b37 | 6e61323dca4762a0d858c601f46a67029d016c8a | /R/VaRES_evt.R | 0e9c8b1716562995663f03605069ca877b068a20 | [] | no_license | lnsongxf/MidasVaREs | c9b562595e6ad64d30a560d2fca2981a04ec007d | a9541a601ab69f9dca29dbfaed6c86f36501e71a | refs/heads/master | 2020-12-03T18:17:57.643118 | 2019-01-29T13:31:27 | 2019-01-29T13:31:27 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 7,570 | r | VaRES_evt.R | #--------------------------------
# MAIN FUNCTIONS: Estimate MIDAS quantile regression
#--------------------------------
#' @importFrom fExtremes gpdFit
#' @export VarEs_evt
VarEs_evt <- function(y,yDate,x = NULL, xDate = NULL, q = 0.01,qThreshold = 0.075,multiSol = TRUE,Params = NULL,
horizon = 10, nlag = 100, ovlap = FALSE, numInitialsRand = 50000, constrained = FALSE,
numInitials = 20, GetSe = FALSE, GetSeSim = 200, startPars = NULL, forecastLength = 0,
MainSolver = "bobyqa",SecondSolver = "ucminf",quantEst = "midas", As = FALSE, empQuant = NULL,
fitcontrol = list(rep = 5),beta2para = FALSE,warn = TRUE, simpleRet = FALSE,Uni = TRUE){
#-- set up arguments ----
if(length(yDate) != length(y)) stop("\nMidasQuantile-->error: Length of y and yDate should be the same\n")
if(is.na(match(quantEst,c("midas","cav")))){
stop("\nError: the quantile regression should be either midas or cav..\n")
}
if(is.na(match(MainSolver,c("bobyqa","ucminf","neldermead","solnp","bfgs")))){
stop("\nMidasQuantile-->error: available solvers are bobyqa, ucminf and neldermead... \n")
}
if(!is.null(SecondSolver)){
if(is.na(match(SecondSolver,c("bobyqa","ucminf","neldermead","solnp","bfgs")))){
stop("\nMidasQuantile-->error: Available solvers are bobyqa, ucminf and neldermead... \n")
}
}
#------ Get the threshold for the extreme value theory-----
VaRthreshold <- switch (quantEst,
cav = CAViaR(y = y, yDate = yDate, x = x, q = qThreshold, horizon = horizon, ovlap = ovlap, numInitialsRand = numInitialsRand,
numInitials = numInitials, empQuant = empQuant, GetSe = GetSe, startPars = startPars,multiSol = multiSol,
MainSolver = MainSolver,SecondSolver = SecondSolver, As = As, fitcontrol = list(rep = 5),Params = Params,
warn = warn, simpleRet = simpleRet, Uni = Uni, forecastLength = forecastLength, constrained = constrained),
midas = MidasQuantile(y = y, yDate = yDate, x = x, xDate = xDate, q = qThreshold, horizon = horizon, nlag = nlag, ovlap = ovlap,
numInitialsRand = numInitialsRand, numInitials = numInitials, GetSe = GetSe, GetSeSim = GetSeSim, Params = Params,
startPars = startPars, MainSolver = MainSolver, SecondSolver = SecondSolver, As = As, fitcontrol = fitcontrol,
beta2para = beta2para, warn = warn, constrained = constrained, simpleRet = simpleRet, forecastLength = forecastLength,multiSol = multiSol)
)
#------ Estimate the General Pareto Distribution parameters----
if(VaRthreshold$conv == 1){
warning("\nThe quantile regression for threshold level is not converged, refit the model with other solver...\n")
out = list(estPars = NA,thresholdEst = NA, yLowFreq = y, yDate = yDate, condVaR = NA,condES = NA,
GPDest = NA, quantile = q, beta2para = beta2para, Solvers = c(MainSolver,SecondSolver), simpleRet = simpleRet,
As = As, Uni = Uni, forecastLength = forecastLength,empQuant = empQuant, quantEst = quantEst, conv = 1)
} else{
condThres = VaRthreshold$condVaR
y = VaRthreshold$yLowFreq
yDate = VaRthreshold$yDate
StdExceed = y/condThres - 1
GPDfit = try(fExtremes::gpdFit(x = StdExceed,u = 0),silent = TRUE)
if(inherits(GPDfit,"try-error")){
warning("\n Unrealistic estimate of GPD paramters or positive condVaR, reestimate with another threshold level..\n")
out = list(estPars = NA,thresholdEst = VaRthreshold, yLowFreq = y, yDate = yDate, condVaR = NA,condES = NA,
GPDest = NA, quantile = q, beta2para = beta2para, Solvers = c(MainSolver,SecondSolver), simpleRet = simpleRet,
As = As, Uni = Uni,ovlap = ovlap, forecastLength = forecastLength,empQuant = empQuant, quantEst = quantEst, conv = 1, horizon = horizon)
}else{
GPDpars = GPDfit@fit$par.ests
gamma = GPDpars[1]; beta = GPDpars[2]
Threshold_ViolateRate <- VaRthreshold$ViolateRate
StdQuantile = ((q*(1/Threshold_ViolateRate))^(-gamma)-1)*(beta/gamma)
condVaR = condThres * (1 + StdQuantile)
ExpectedMean_StdQuant = StdQuantile * (1/(1-gamma) + beta/((1-gamma)*StdQuantile))
condES = condThres * (1 + ExpectedMean_StdQuant)
if(gamma >= 1 || any(condVaR >= 0)){
warning("\n Unrealistic estimate of GPD paramters or positive condVaR, reestimate with another threshold level..\n")
out = list(estPars = c(VaRthreshold$estPars,unname(GPDfit@fit$par.ests)),thresholdEst = VaRthreshold, yLowFreq = y, yDate = yDate, condVaR = condVaR,condES = condES,
GPDest = GPDfit, quantile = q, beta2para = beta2para, Solvers = c(MainSolver,SecondSolver), simpleRet = simpleRet,
As = As, Uni = Uni,ovlap = ovlap, forecastLength = forecastLength,empQuant = empQuant, quantEst = quantEst, conv = 1, horizon = horizon)
} else{
ViolateRate <- (sum(y < condVaR))/(length(y))
out = list(estPars = c(VaRthreshold$estPars,unname(GPDfit@fit$par.ests)),thresholdEst = VaRthreshold, yLowFreq = y, yDate = yDate, condVaR = condVaR,condES = condES,
GPDest = GPDfit, quantile = q, beta2para = beta2para, Solvers = c(MainSolver,SecondSolver), simpleRet = simpleRet,
As = As, Uni = Uni,ovlap = ovlap, forecastLength = forecastLength,empQuant = empQuant, quantEst = quantEst, horizon = horizon, ViolateRate = ViolateRate, conv = 0)
}
}
}
return(out)
}
#---------------------------------
# Forecasting function
#----------------------------------
#' @export VarEs_evt_for
VarEs_evt_for <- function(object, y, yDate, x = NULL, xDate = NULL){
#--------- Recall InSample arguments-----
quantEst <- object$quantEst; estPars = object$estPars; ISthresholdEst = object$thresholdEst; q = object$quantile
beta2para = object$beta2para; simpleRet = object$simpleRet; As = object$As; Uni = object$Uni;
quantEst = object$quantEst; horizon = object$horizon;ovlap = object$ovlap
#----- Get the condVaR and condEs -----
n = length(estPars)
gamma = estPars[n-1]; beta = estPars[n]
VaRthreshold <- switch (quantEst,
cav = CAViaRfor(object = ISthresholdEst, y = y, yDate = yDate, x = x, xDate = xDate),
midas = MidasQuantileFor(object = ISthresholdEst, y = y, yDate = yDate, x = x, xDate = xDate))
VaRthreshold = VaRthreshold$OutSample
condThres = VaRthreshold$condVaR
y = VaRthreshold$yLowFreq
yDate = VaRthreshold$yDate
StdExceed = y/condThres - 1
IS_Threshold_ViolateRate <- ISthresholdEst$ViolateRate
StdQuantile = ((q*(1/IS_Threshold_ViolateRate))^(-gamma)-1)*(beta/gamma)
condVaR = condThres * (1 + StdQuantile)
ExpectedMean_StdQuant = StdQuantile * (1/(1-gamma) + beta/((1-gamma)*StdQuantile))
condES = condThres * (1 + ExpectedMean_StdQuant)
ViolateRate <- (sum(y < condVaR))/(length(y))
OSout = list(yLowFreq = y, yDate = yDate, condVaR = condVaR,condES = condES,VaRthreshold = VaRthreshold,
quantile = q, beta2para = beta2para, simpleRet = simpleRet,
As = As, Uni = Uni,quantEst = quantEst, ViolateRate = ViolateRate)
out <- list(InSample = object, OutSample = OSout)
return(out)
}
|
5c281f71e3b15e94c0cefda06e67634895c7479f | 4d07eecae0429dc15066b34fbe512b8ff2ae53ea | /mds/intexp/smoothKDE.R | f3f8ec546479050c31795ac97f53d2e4ed2226c0 | [] | no_license | distanceModling/phd-smoothing | 7ff8ba7bace1a7d1fa9e2fcbd4096b82a126c53c | 80305f504865ce6afbc817fff83382678864b11d | refs/heads/master | 2020-12-01T09:31:24.448615 | 2012-03-27T18:35:45 | 2012-03-27T18:35:45 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 3,447 | r | smoothKDE.R | # thin plate spline with squash
# taken from smooth.r in mgcv
# 2D version! KDE hack
## The constructor for a tprs basis object with MDS modifications.
smooth.construct.mdstp.smooth.spec<-function(object,data,knots){
library(ks)
if(length(names(data))!=2){
cat("mdstp can only be used with 2D smooths!\n")
return(1)
}
# make the tprs object as usual
object<-smooth.construct.tp.smooth.spec(object,data,knots)
## recreate the S matrix
# use finite difference to find the second derivatives
eps<-(1e-15)^(1/4)
oldS<-object$S[[1]]
k<-dim(object$S[[1]])[1]
N<-100
### first need to create the mesh we want to integrate over
# mesh function
mesh <- function(x,d,w=1/length(x)+x*0) {
n <- length(x)
W <- X <- matrix(0,n^d,d)
for (i in 1:d) {
X[,i] <- x;W[,i] <- w
x<- rep(x,rep(n,length(x)))
w <- rep(w,rep(n,length(w)))
}
w <- exp(rowSums(log(W))) ## column product of W gives weights
list(X=X,w=w) ## each row of X gives co-ordinates of a node
}
# take the boundary
# map it into the space
bnd<-object$xt$bnd
int.bnd<-bnd
bnd.mds<-insert.mds(int.bnd,object$xt$op,object$xt$mds.obj,bnd,faster=0)#,debug=1)
bnd.mds<-data.frame(x=bnd.mds[,1],y=bnd.mds[,2])
#plot(bnd.mds,type="l")
# set the integration limits
# just make an overly big bounding box
a<-min(c(bnd.mds$x,bnd.mds$y))
b<-max(c(bnd.mds$x,bnd.mds$y))
# take a grid in the mds space
ip <- mesh(a+(1:N-.5)/N*(b-a),2,rep(2/N,N))
# knock out those points outside the boundary
onoff<-inSide(bnd.mds,ip$X[,1],ip$X[,2])
ep<-list()
ep$X<-ip$X[onoff,]
ep$w<-ip$w[onoff]
# plot the integration grid
#plot(ep$X,pch=19,cex=0.3)
#lines(bnd.mds,type="l",col="red")
#X11()
# root the weights, since we square them in a bit
ep$w<-sqrt(ep$w)
# let's create some matrices
# finite second differences wrt x and y
dxee<-Predict.matrix(object,data.frame(x=ep$X[,1]+2*eps,y=ep$X[,2]))
dxe <-Predict.matrix(object,data.frame(x=ep$X[,1]+eps,y=ep$X[,2]))
dyee<-Predict.matrix(object,data.frame(x=ep$X[,1],y=ep$X[,2]+2*eps))
dye <-Predict.matrix(object,data.frame(x=ep$X[,1],y=ep$X[,2]+eps))
dxy <-Predict.matrix(object,data.frame(x=ep$X[,1],y=ep$X[,2]))
dxye<-Predict.matrix(object,data.frame(x=ep$X[,1]+eps,y=ep$X[,2]+eps))
Dx<-ep$w*(dxee-2*dxe+dxy)/eps^2
Dy<-ep$w*(dyee-2*dye+dxy)/eps^2
Dxy<-ep$w*(dxye-dxe-dye+dxy)/eps^2
#this.dat<-eval(parse(text=paste("data$",object$term,sep="")))
this.dat<-matrix(c(data$x,data$y),length(data$x),2)
dens.est<-kde(this.dat,H=Hpi(this.dat),eval.points=ep$X)
sq<-sqrt(((1/dens.est$estimate)^3)/sum((1/dens.est$estimate)^3))
#################################################
# do the squashing
# sq<-sqrt((dens.est)^3)
Dx<-sq*Dx
Dy<-sq*Dy
Dxy<-sq*Dxy
# actually do the integration
S<-t(Dx)%*%Dx + t(Dxy)%*%Dxy + t(Dy)%*%Dy
# enforce symmetry (from smooth.construct.tp...)
S <- (S + t(S))/2
# store the object
object$S[[1]]<-S
# zero the last three rows and cols
object$S[[1]][(k-2):k,]<-rep(0,k*3)
object$S[[1]][,(k-2):k]<-rep(0,k*3)
# uncomment to return the old version of S
#object$oldS<-oldS
class(object)<-"mdstp.smooth"
object
}
# prediction matrix method
Predict.matrix.mdstp.smooth<-function(object,data){
Predict.matrix.tprs.smooth(object,data)
}
|
4b376db3a52de96ddc1a977462832a77472b6bad | 941bcfc6469da42eec98fd10ad1f3da4236ec697 | /tests/testthat/test-track_distance.R | 4fdaa87267cd2c63b80ae3aa155f7ea47eb05be6 | [] | no_license | cran/traipse | 29c3fd65e98f65049da98b1d878512bfdd93940f | 01635fd40512f2144e1ce712e0f5912143214e49 | refs/heads/master | 2022-10-22T02:59:19.828085 | 2022-10-10T06:40:02 | 2022-10-10T06:40:02 | 236,953,410 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 181 | r | test-track_distance.R | test_that("distance works", {
expect_equivalent(round(track_distance(c(0, 0, 1, 0), c(0, 1, 1, 0)), digits = 2L),
c(NA, 110574.39, 111302.65, 156899.57))
})
|
8a1139a087db22adbafe9768e43a646c9bf76821 | ffdea92d4315e4363dd4ae673a1a6adf82a761b5 | /data/genthat_extracted_code/SYNCSA/examples/belonging.Rd.R | b4c80673f245b8eeafc49f807789a575008cccf0 | [] | no_license | surayaaramli/typeRrh | d257ac8905c49123f4ccd4e377ee3dfc84d1636c | 66e6996f31961bc8b9aafe1a6a6098327b66bf71 | refs/heads/master | 2023-05-05T04:05:31.617869 | 2019-04-25T22:10:06 | 2019-04-25T22:10:06 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 178 | r | belonging.Rd.R | library(SYNCSA)
### Name: belonging
### Title: Degree of belonging of species
### Aliases: belonging
### Keywords: SYNCSA
### ** Examples
data(ADRS)
belonging(ADRS$phylo)
|
e9196de6707a16e8d5345c3a44ca74832d96ad3c | 256f220648296026714d24947d25be71c9d5cf09 | /spikein_free_algorithm_benchmark.R | d8bbcfe93d96626d6aee53ac9d9227c89650330e | [] | no_license | Xiaojieqiu/Census_BEAM | f07f9d37f20646469a14f9e88d459b1b6046d662 | b84a377f5890bc7829dc1565c4c4d2dc2c824f83 | refs/heads/master | 2021-03-22T05:03:42.708956 | 2015-11-14T20:12:17 | 2015-11-14T20:12:17 | 45,900,189 | 0 | 1 | null | null | null | null | UTF-8 | R | false | false | 1,726 | r | spikein_free_algorithm_benchmark.R | load('prepare_lung_data.RData')
library(monocle)
library(xacHelper)
load_all_libraries()
############################make the landscape heatmap:
mc_select <- coef(rlm(unlist(lapply(molModels_select, function(x) coef(x)[1])) ~ unlist(lapply(molModels_select, function(x) coef(x)[2]))))
optim_mc_func_fix_c_test_optim(c(as.numeric(mc_select[2]), as.numeric(mc_select[1])))
x_list <- split(expand.grid(c(seq(-6, -1, length.out = 2), -4.403166, as.numeric(mc_select[2])),
c(seq(0, 4, length.out = 2), 2.77514, as.numeric(mc_select[1]))), 1:16)
# test the function: whether or not it will run fine
optim_mc_func_fix_c_test_optim(x_list[[1]])
# mclapply cannot deal with situations when NAs are returned
# optimization_landscape_3d <- mclapply(X = split(expand.grid(c(seq(-6, -1, length.out = 100), -4.403166, as.numeric(mc_select[2])),
# c(seq(0, 4, length.out = 100), 2.77514, as.numeric(mc_select[1]))), 1:102^2), optim_mc_func_fix_c_test_optim, mc.cores = detectCores())
optimization_landscape_3d <- lapply(X = split(expand.grid(c(seq(-6, -1, length.out = 100), -4.403166, as.numeric(mc_select[2])),
c(seq(0, 4, length.out = 100), 2.77514, as.numeric(mc_select[1]))), 1:102^2), optim_mc_func_fix_c_test_optim)
# #this doesn't work, need to use roster and sp:
# optimization_landscape_2d <- melt(optimization_landscape_3d)
# pdf('eLife_fig4E.pdf')
# qplot(Var1, Var2, fill=optim_res, geom="tile", data=optimization_landscape_2d) + scale_fill_gradientn(colours=rainbow(7)) #hmcols
# # ggsave(filename = paste(elife_directory, 'eLife_fig4E.pdf', sep = ''), width = 1.38, height = 1.25)
# dev.off()
save.image('spikein_free_algorithm_benchmark.RData')
|
bcfc998dcbc734f3771ca951ad2d649aab13c4ee | 01b17881e85527fcb28e00d134ab758e8c93076b | /cachematrix.R | 3c2e794c42a276a82f6718b55fb2af6110b3f6a1 | [] | no_license | elibus/ProgrammingAssignment2 | 6d4136f78d994859edcf16b4d325106a9d3221b5 | 51788a4dda2fc400b5e8919ff26fb2b43ccb1ab3 | refs/heads/master | 2021-01-22T12:36:41.814182 | 2015-06-19T11:24:23 | 2015-06-19T11:24:23 | 37,713,890 | 0 | 0 | null | 2015-06-19T09:37:23 | 2015-06-19T09:37:23 | null | UTF-8 | R | false | false | 655 | r | cachematrix.R | ## Compute matrix inversion w/ cache
## Wraps a matrix object to add caching functionalities
makeCacheMatrix <- function(x = matrix()) {
inv <- NULL
get <- function()
x
setInv <- function(m)
inv <<- m
getInv <- function()
inv
list(
get = get,
setInv = setInv,
getInv = getInv
)
}
## Cached version of solve() to compute matrix inversion
## To be used on objects created with makeCacheMatrix()
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
inv <- x$getInv()
if (!is.null(inv)) {
return(inv)
}
m <- x$get()
inv <- solve(m, ...)
x$setInv(inv)
inv
}
|
97c4ad35bfc4e7ded0b96a54cd88cbe2b031ad44 | 8977a8c56a27e68d3436b5b0ef96016ce1b7b9de | /Salaries.R | 647941694ffa1be663ef9c7243e5bd5e2ca6a96a | [] | no_license | jcval94/Random_Projects | 9d680592fa7eaecb1fb0ea5df84ffd4c259a98fe | ee940a029010580e6089a4463b0b5b72aeb66423 | refs/heads/master | 2020-12-14T04:50:32.844979 | 2020-05-05T03:54:46 | 2020-05-05T03:54:46 | 234,645,600 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,513 | r | Salaries.R | #https://www.youtube.com/watch?v=nx5yhXAQLxw&t=2224s
library(ggplot2)
library(tidyverse)
major_DB<-read.csv("https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2018/2018-10-16/recent-grads.csv")
major_DB %>% names()
major_DB %>% head()
#Graficaremos los salarios por carera
major_DB %>% filter(Sample_size>50) %>% group_by(Major_category) %>%
mutate(median_sal=median(Median)) %>%
arrange(desc(median_sal)) %>% #head(15) %>%
ggplot(aes(reorder(Major_category,median_sal),median_sal))+
geom_col()+coord_flip()
#Plot con los quartiles y rangos
#Median P25th P75th
Unemployment_rate<- major_DB %>% filter(Sample_size>50) %>%
select(Major,Median,Unemployment_rate)
Unemployment_rate %>% ggplot(aes(Median,Unemployment_rate))+
geom_point()
Unemployment_rate %>% arrange(desc(Unemployment_rate)) %>% head(15) %>%
ggplot(aes(reorder(Major,Unemployment_rate),Unemployment_rate))+
geom_col()+coord_flip()
major_DB %>%
group_by(Major) %>%
arrange(desc(Median)) %>%
head(20) %>%
ggplot(aes(reorder(Major,Median),Median))+
geom_point()+
geom_errorbar(aes(ymin=P25th,ymax=P75th))+
coord_flip()
major_DB %>%
group_by(Major_category) %>%
mutate(Mediana_M=median(Median),Mediana_25=median(P25th),Mediana_75=median(P75th)) %>%
arrange(desc(Median)) %>%
#select(Major_category,Mediana_M)%>%
#head(20) %>%
ggplot(aes(reorder(Major_category,Mediana_M),Mediana_M))+
geom_point()+
geom_errorbar(aes(ymin=Mediana_25,ymax=Mediana_75))+
coord_flip()
|
670ad2643fb943b90c224e6305fe243c5ec054fa | 9ed38aa06528612925ed9aeca637b03c33ad317b | /R/oldies/struc_enet.R | f69045f6bb1688eeedd1eb9d07e4e1e5c37401f1 | [] | no_license | cambroise/sparsity-quadratic-penalties | 13d72800888b2fa5fd79052aca913d61eb7e4134 | 8352de4534147c3c66a69f5ca02f484f52bb72e1 | refs/heads/master | 2021-05-08T23:26:31.066736 | 2018-04-30T13:29:48 | 2018-04-30T13:29:48 | 119,706,970 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 832 | r | struc_enet.R | rm(list=ls())
gc()
library(elasticnet)
library(R.utils)
sourceDirectory("functions")
seed <- sample(1:10000,1)
set.seed(seed)
p <- 100
n <- 200
beta <- rep(c(0,2,0,-2),each=5)
beta <- rep(beta,p%/%20)
data <- example_c_enet(n, beta, cor=0.25)
x <- data$x
y <- data$y
D <- matrix(0,p,p)
for (k in 1:20) {
D[((k-1)*5+1):(k*5),((k-1)*5+1):(k*5)] <- 0.9
}
diag(D) <- 1
out.lass <- crafter(x, y, gamma=0)
out.enet <- crafter(x, y, gamma=1)
out.stru <- crafter(x, y, gamma=1, D)
par(mfrow=c(1,3))
plot(out.stru$fit, main="Structured Enet, gamma=10",
xvar="fraction", col=rep(1:20,each=5), lty=rep(1:20,each=5))
plot(out.enet$fit, main="Elastic-net, gamma=10",
xvar="fraction", col=rep(1:20,each=5), lty=rep(1:20,each=5))
plot(out.lass$fit, main="Lasso",
xvar="fraction", col=rep(1:20,each=5), lty=rep(1:20,each=5))
|
59c9a7563f663fd1f1340249abd4a1a85419f99a | 7259c1a7c14c87c073b1896eb4830b901e994a8d | /R/cohort_table_day.R | ad2ea8244ee781da879c15a9113ef6ce1171b800 | [
"MIT"
] | permissive | romainfrancois/cohorts | 236281bdd899175609045b7da06119319dd296df | a8e7a0009b4cf132142105a29aeddb81b5dbd008 | refs/heads/main | 2023-06-15T19:32:17.100022 | 2021-07-11T21:13:00 | 2021-07-11T21:13:00 | null | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 833 | r | cohort_table_day.R | #' Create a Cohort Table Using Day Level Event Data
#'
#' Creates a cohort table with day level event data with rows corresponding to cohort numbers and columns as dates.
#' @param df Dataframe
#' @param id_var ID variable
#' @param date Date
#'
#' @return Cohort table
#'
#' @export
#' @examples
#' cohort_table_day(gamelaunch, userid, eventDate)
#'
#'
cohort_table_day <- function(df, id_var, date) {
dt <- dtplyr::lazy_dt(df)
dt %>%
dplyr::group_by({{id_var}}) %>%
dplyr::mutate(cohort = min({{date}})) %>%
dplyr::group_by(cohort, {{date}}) %>%
dplyr::summarise(users = dplyr::n()) %>%
tidyr::pivot_wider(names_from={{date}},values_from=users) %>%
dplyr::ungroup() %>%
dplyr::mutate(cohort = 1:dplyr::n_distinct(cohort)) %>%
tibble::as_tibble()
}
utils::globalVariables(c("cohort","users"))
|
a9da73d077f3bfa6353545aad448e4a2d0217847 | 1e2be94889b961e08558884f36f7c6fa3a1a1567 | /plot6.R | 5532316ba0040a6a75d73588e0bb352a1c4f148e | [] | no_license | enwude/exdata_data_NEI_data | 15ad81a05a8d061f1660fc757a0206faf49380c0 | 873dcd5fd5121ce6b36bad40723c5d050ed7d348 | refs/heads/master | 2021-01-10T00:53:49.625794 | 2015-08-23T01:21:07 | 2015-08-23T01:21:07 | 41,127,399 | 0 | 0 | null | null | null | null | UTF-8 | R | false | false | 1,991 | r | plot6.R | library(ggplot2)
library(dplyr)
# Create working directory if necessary
if(!file.exists("~/Data/")){
dir.create("~/Data/")
}
# Determine if dataset has been loaded to global environment
if(!exists("NEI", envir = globalenv()) | !exists("SCC", envir = globalenv())){
# Download and unzip the data
fileUrl <- "https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2FNEI_data.zip"
download.file(fileUrl, destfile = "~/Data/exdata_data_NEI_data/NEI_data.zip")
unzip(zipfile = "~/data/exdata_data_NEI_data/NEI_data.zip", exdir = "~/data/exdata_data_NEI_data")
# Set working directory
datasetPath <- "~/data/"
setwd(file.path(datasetPath, "exdata_data_NEI_data"))
# Read data to R
NEI <- readRDS("summarySCC_PM25.rds")
SCC <- readRDS("Source_Classification_Code.rds")
}
# Launch png graphics device
png("plot6.png", width = 861, height = 532)
# create SCC data subset with motor vehicle emissions in Baltimore and Los Angeles
motorData <- grepl("vehicles", SCC$EI.Sector,ignore.case = TRUE)
motorData <- subset(SCC,motorData)
Balt.LA.Emit <- subset(NEI, fips == "24510" | fips == "06037")
# create NEI data subset with motor vehicle emissions in Baltimore and Los Angeles
Balt.LA.Vehicle <- Balt.LA.Emit[Balt.LA.Emit$SCC %in% motorData$SCC,]
# rename zip code with city names
Balt.LA.Vehicle <- mutate(Balt.LA.Vehicle, fips = gsub("24510", "Baltimore City", fips))
Balt.LA.Vehicle <- mutate(Balt.LA.Vehicle, fips = gsub("06037", "Los Angeles", fips))
# plot Emissions vs Year using ggplot2
Balt.LA.Plot <- ggplot(Balt.LA.Vehicle, aes(factor(year),Emissions,fill = factor(year)))
Balt.LA.Plot + geom_bar(stat="identity") + labs(title = expression("PM"[2.5]*" Emissions from motor vehicle sources in Baltimore City & Los Angeles")) +
xlab("Year") + ylab(expression("PM"[2.5]*" Emissions")) + facet_grid(.~fips) + guides(fill=guide_legend(title="Year"))
dev.off() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.