Professional Documents
Culture Documents
קודיםR
קודיםR
$
# מאפשר לגשת למשהו ספציפי (עמודה) במידע
Plots- גרפים
#basic plot function
plot(data$Y,data$X)
#density plot
plot(density(mydata$loudness))
# ggplot2
install.packages("ggplot2")
library(ggplot2)
x<-ggplot(data=mydata,aes(x=danceability,y=liveness))+ geom_point()
רגרסיה פשוטה:
y<-df$Y
x<-df$x
mult_Reg<-function(b)
{pred_y=b[1]+b[2]*x
res_y<-sum((y-pred_y)^2)
return(res_y)}
a = b1 #
y<-df$Y
x1<-df$x1
x2<-df$X2
mult_Reg<-function(b)
{pred_y=b[1]+b[2]*x1+ b[3] *x2
res_y<-sum((y-pred_y)^2)
return(res_y)}
a = b1 #
output<-nlminb(c(100,100),mult_Reg)
output$par
) ואני נותנת לאלגוריתם לרוץx,y( פיתרון נומרי שאני נותנת לו שני ערכי התחלה#
. שלי עבור אותם ערכיםb- ואת הa -עליהם ומקבלת את ה
#full model-Predicting something using all of the other variables in the data
fullmodel<-lm(satov~.,data=fulldata)
summary(fullmodel)
והיא מייצגת את כלdata,. - מודל שמנבא על פי כל המשתנים לכן כותבים נקודה#
.)המשתנים (במקום לכתוב את כל השמות
model1<-lm(data$Y~data$X1+ data$X2)
summary(model1)
# בניית מודל
:רגרסיה היררכית
#Hierarchical regression
install.packages("olsrr")
library(olsrr)
:גישה שכיחותנית
model1<-lm(y~x1+x2, data=data)
summary(model1)
# building another model, in which we test the added variables effect (block 2):
model2<-lm(y~x1+x2+x3+x4, data=data)
summary(model2)
anova(model1,model2)
)= התוספת לשונות המובהקת (שנתנו לנו המשתנים שהוספנו בבלוק השני5.5228
במקרה הזה היא," אנחנו רואים את המובהקות של התוספתF Pr(>F)" בעמודה שהכותרת שלה היא
.לא מובהקת
:גישה בייסיאנית
#Bayesian lm:
install.packages("BayesFactor")
library(BayesFactor)
מזה אנחנו מקבלים פלט עם על ה BF-של כל המודלים האפשריים (עם מנבא אחד ,עם שני מנבאים,
עם שלושה)....
אם אנחנו רוצים לצמצם את האופציות:
(מהפלט הזה אנחנו רואים שבמקרה הזה דיכאון לבד מנבא הכי טוב)
]model[1]/model[22
(שמים את המספרים של שני המודלים שביניהם אני רוצה להשוות ,המספרים שמייצגים כל מודל הם
לפי הפלט שמקבלים מה summery-ולא מפקודת ")"head
בפלט הזה השוו בין מודל [( ]1עם מנבא דיכאון) לבין המודל האחרון (עם כל המנבאים).
=1650.463פי כמה מודל [ ]1יותר סביר ממודל [( .]22זה מראה לנו שממש עדיף לנבא רק עם
דיכאון)
data$c1[data$drug=="placebo"]<- -0.5
data$c1[data$drug=="anxifree"]<- -0.5
data$c1[data$drug=="joyzepam"]<- 1
data$c2[data$drug=="placebo"]<- -1
data$c2[data$drug=="anxifree"]<- 1
data$c2[data$drug=="joyzepam"]<- 0
# make sure that the contrasts are orthogonal.
#Now we will check which contrast is statisticaly significent:
# Where does the effect at drugs comes from? - To answer that question, we will
need to know the
# actual means of each group. We can get the means via normal R syntax, or by use
of 'dplyr' syntax:
#We can see that the 'jotzepam' mean is larger then the rest of the means.
# And since the contrasts told us that there is a significent effect, we can conclude
that these mean differences from 'joyzepam' to the rest of the drugs are statistically
significant.
לאחר שאני רואה שיש מובהקות אני בודקת את הקונטרסטים כדי לראות מאיפה#
:המובהקות באה
c1= joyzepam vs. anxifree + placebo
c2= anxifree vs. placebo
data$c1[data$drug=="anxifree"]<- -0.5
data$c1[data$drug=="joyzepam"]<- 1
data$c1[data$drug=="placebo"]<- -0.5
data$c2[data$drug=="anxifree"]<- -1
data$c2[data$drug=="joyzepam"]<- 0
data$c2[data$drug=="placebo"]<- 1
data$c1<-as.numeric(data$c1)
data$c2<-as.numeric(data$c2)
model1 <- aov(mood.gain ~ c1+c2, data = data)
summary(model1)
במידה. השני והאינטראקציה, כשמכפילים בין משנים מקבלים האפקט העיקרי הראשון#
ורוצים לבדוק גם אינטראקציה משולשת וכו' אני אכפיל בגורם השלישי ואקבל אפקטים
. את כל האינטראקציות הזוגיות ואת המשולשות,עיקריים
modelsame <- aov(y ~ x1*x2, data = data2)
summary(modelsame)
:dummy coding
colnames(data2)
# 1) Research question: math score as function of completing test preparation course
#3 ) Which one is the base variable and which one is not? -- answer: the base
variable is the one that is not
#presented in the summary(). In our case, the 'completed' level is the base level
since it's not in our summary()
# this returns the coding that R have used to create the dummy variables:
contrasts(factor(data2$test.preparation.course)) # Notice the factr()! the contrasts()
function only
# deals with factorial variables so we have to transform our variables into factorial
type.
library(QuantPsyc)
model<- lm (Y~.,data=data)
model2<- lm.beta(model)
model2
:Overfitting
:Adjusted R^2
summary (model)$r.squared
R2 חישוב#
summary (model)$adj.r.squared
adjusted R2 חישוב#
R<-
K<-
N<-
Adjusted<-(R^2)-((K*(1-(R^2)))/(N-K-1))
Adjusted
תיקוף צולב:
set.seed(101)
dgima <- sample.int(n = nrow(fulldata), size = floor(.8*nrow(fulldata)),
replace = F)
# 0.8 is for the size of the train set
train <- fulldata[dgima, ]
test <- fulldata[-dgima, ]
k-fold cv:
# Define training control
install.packages("caret")
library(caret)
set.seed(123)
train.control <- trainControl(method = "cv", number = 10)
. control- ומה הtraining - פונקציה המגדירה מה ה-trainControl #
) (מספר קבוצותnumber=k
# Train model
model <- train(satov~., data = fulldata, method = "lm",
trControl = train.control)
# Summarize the results
print(model)
:ליניאריות
. נראה אם יש מגמתיות: עבור כל אחד מהמשתנים שאני רוצה לבדוק#
#Testing the linearity assumption
plot(data$X~data$Y)
: אם הליניאריות לא יצאה מובהקת אפשר לתקן את המשתנים#
#if not linear
plot(data$X~log(data$Y))
נבנה את המודל#
#Build a model
mymodel<-lm(Y~X1+X2,data=data)
summary(mymodel)
:נורמאליות
plot(mymodel, 2)
) (בטעיות:הומוסקדסטיות
#Testing the Homoscedasticity Assumption
plot(mymodel, 1)
#or - another way to get the same plot.
#install.packages("olsrr")
library(olsrr)
ols_plot_resid_fit(mymodel)
:מולטיקולינאריות
install.packages("olsrr")
library(olsrr)
#Collinearity Diagnostics - get the Tolerance
ols_vif_tol(mymodel)
(טולרנס חלקי אחד) (ההפוך) אנוVIF בעמודת, רוצים תוצאה גבוההtoleranc בעמות#
הפלט מימין הוא. זה עונה על השאלה כמה אחד מתואם על השאר.רוצים תוצאה נמוכה
67% עמידהcatholic , למשל.השוואה בין שלושה משתנים והפלט משמאל שני משתנים
.ביחס לאחרים
בבחירת מנבאים נרצה את המנבא עם הטולרנס הגבוהה ביותר הוא בשורה האחרונה של#
.)הפלט (המנבאים מופיעים בסדר עולה מהטולרנס הנמוך לגבוה
מתאם חלקי:
ppcor$estimate
:מתאם חלק
(כפי שניתן לראות ,בין happiness.scoreלבין social_supportיש מתאמים שונים בנקודות החיתוך
ביניהם .לפי מה שנאמר בתרגול ,לא ניתן לדעת באיזה מהם המשתנה generosityהוחזק קבוע
לאיזה משתנה ,נאמר שתינתן תשובה בנושא בהמשך)
:החזקת קבוע
calculate e from Y#
correlation#
) שמים את המשתנה הרגילres- במקום אחד מציוני ה,(אם רוצים לעשות מתאם חלק#
:מיתון
x1 <- scale(data$x1,scale = F)
x2 <- scale(data$x2,scale = F)
#2. calculating a third independent variable which represents the moderation: חישוב משתנה
מכפלת המשתנים הממורכזים-בלתי תלוי נוסף שמבטא את המיתון
# moderation plot:
a<-sum_mod$coefficients[1]
b1<-sum_mod$coefficients[2]
b2<-sum_mod$coefficients[3]
b3<-sum_mod$coefficients[4]
# defining which levels of moderator we want to plot (sd+, sd-, and mean):
inhibitionHI<-sd(data$inhibition_centered)
inhibitionLO<-sd(data$inhibition_centered)*-1
slopeHI=b1+b3*inhibitionHI
slopeZero=b1
slopeLO=b1+b3*inhibitionLO
interHI=a+b2*inhibitionHI
interZero=a
interLO=a+b2*inhibitionLO
# plotting
install.packages("ggplot2")
library(ggplot2)
p<-ggplot(data=data,aes(hindrance_centered,negative.affect))
pp<-p+geom_point()
pp
fun_HI<-function(hindrance_centered) interHI + hindrance_centered * slopeHI
fun_M<-function(hindrance_centered) interZero + hindrance_centered * slopeZero
fun_LO<-function(hindrance_centered) interLO + hindrance_centered * slopeLO
pp+stat_function(fun=fun_HI,aes(color="+sd")) + stat_function(fun=fun_M) +
stat_function(fun=fun_LO,aes(color="-sd"))
תיווך:
install.packages("medmod")
library(medmod)
# building a model:
medmodel<-med(data=data, dep=y, med=m, pred=x, estMethod = "bootstrap",
bootstrap = 1000)
medmodel
data$x<-data$x
data$y<-data$y
data$m<-data$m
modalc<-lm(y~x,data=data)
summary(modalc)
modela<-lm(m~x,data=data)
summary(modela)
modelb<-lm(y~x+m,data=data)
summary(modelb)
:פלטים
:בחירת מנבאים
# Building a model:
model<-lm(y~.,data=data)
summary(model)
# 1 Forward selection
step_forward_model<-ols_step_forward_p(model)
step_forward_model$model #gives us the selected variables and their beta
# 2 Backward selection
step_backward_model<-ols_step_backward_p(model)
step_backward_model$model
# 3 Stepwise selection
Stepwise_selection_model<-ols_step_both_p(model)
Stepwise_selection_model$model
# 4 All possible subsets:
ols_step_all_possible(model)
# 5 Best subset:
ols_step_best_subset(model)
.overfitting מעידה עלAdjusted R ירידה#
:anova באמצעות היררכית אשווה בין המודלים באמצעות מבחן#
נראה כי המודל העליון (במקרה זה המודל ללא מנבאים ) הוא: באמצעות בייסיאנית#
.) (יצא ערך מאוד גבוה.העדיף מפני שהוא מסביר הרבה יותר ביחס למודל בתחתון
. כדי לבנות מודל רגרסיהR- מתייחס לפונקציה שאנו משתמשים בה ב:call -מתחת ל -
.b כל מה שמתחתיו הוא,a הואintercept - ה:estimates בעמודת -
כל מה שבכוכביות הוא מובהק -
.adjusted R , R2 -למטה ניתן לראות את ה
2
-
ליתר ביטחון:
mydata<-na.omit(mydata)
sum(is.na(mydata))
#plot the data- to see if the relationship of Y and X is linear, לבדיקת לינאריות
plot (y~ x)
#how to calculate b?
sd_y<-sd(depression_scores)
sd_x<-sd(income)
sds<-sd_y/sd_x
b<-correlation*sds
b
data<-df
data$Country<-NULL
data<-cor(df2)
corrplot(data,method = "number",tl.cex = 0.7)
#corrplot(data,method = "number")
המתאם ה"אמיתי" לפי שיטה זו.שיטה לתיקון מתאם שחושב על שני מדדים לא מהימנים
. שזה למעשה רוrxy / sqrt(rx1x2 * ry1y2) :שווה ל
חלוקה בשבר. זה המתאם האמיתי,המתאם הנצפה חלקי מכלפת שורשי המהימנויות
אנחנו יכולים להניח שהמתאם100% ואז כל זמן שהמדדים שלנו לא מהימנים ב.מגדילה
. ככל שהמדדים יותר נקיים ומהינים כך הם יעשו לי פחות נזק.שלנו טיפה יותר גדול
# Corrected correlation
Corrected_correlation<-rxy/sqrt(rx1x2 * ry1y2)
Corrected_correlation
לא יכול להיות שבגלל מהימנות גבוהה מאוד ומתאם גבוהה-מהימנות היא חסם עליון לתוקף
.1 מאוד יצא לי בתיקון מעל
data<-read.csv(file.choose(),header=T)
בדיקת מהימנות#
rxy<-cor(data$X,data$Y,method="pearson")
rxy
rx<-
ry<-
תיקון למהימנות#
Corrected<-rxy/sqrt(rx * ry)
Corrected
קיצוץ תחום:
#lets remove some rows
range_restriction<-cor(data2$X,data2$Y,method="pearson")
range_restriction
:b חישוב
#Calculating the squared r with pearson correlation:
correlation<-cor(y,x,method = "pearson")
correlation^2
#Calculating b:
sd_y<-sd(y)
sd_x<-sd(x)
sds<-sd_y/sd_x
b<-correlation*sds
b
#plot a function:
mydata<-data.frame(x,y)
p<-ggplot(data=mydata,aes(x=x,y=y))
pp<-p+geom_point()
pp
a<- להגדיר
b<- להגדיר
fun_HI<-function(x) a + b * x
fun_HI(x)
pp+stat_function(fun=fun_HI,aes(color="red"))