Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
robertopucp
GitHub Repository: robertopucp/1eco35_2022_2
Path: blob/main/Trabajo_grupal/WG1/Grupo_7_r.R
2714 views
1
## Ejercicio 1
2
3
y <- runif(20,0,500)
4
5
for (i in y) {
6
if (i <0 & i <= 100) {
7
next
8
i <- i^(1/2)
9
10
} else if (i > 100 & i <= 300) {
11
i <- i - 5
12
13
} else {
14
i <- 50
15
}
16
y = i
17
}
18
19
print (y)
20
21
22
23
24
## Ejercicio 2
25
26
## Para la matriz
27
28
29
30
sample <- runif(5000,0,500)
31
32
M <- matrix(sample, 100, 50)
33
34
if(! is.matrix(M)) stop("M must be a matrix")
35
36
calculator <- function (M,h,z) {
37
h <- apply(M, 2, min)
38
z <- apply(M, 2, max)
39
40
result = (M - h) / (z - h)
41
return(result)
42
}
43
44
calculator(M, h, z) [1]
45
46
47
# Para el vector
48
49
y <- runif(100,0,500)
50
51
if(! is.vector(y)) stop("y must be a vector")
52
53
calculator1 <- function (y,k,l) {
54
k <- apply(y, 1, min)
55
l <- apply(y, 1, max)
56
57
result = (y - k) / (l - k)
58
return(result)
59
}
60
61
calculator1(y, k, l) [1]
62
63
64
65
66
## Ejercicio 4
67
68
69
x1 <- runif(800)
70
x2 <- runif(800)
71
x3 <- runif(800)
72
x4 <- runif(800)
73
x5 <- runif(800)
74
x6 <- runif(800)
75
x7 <- runif(800)
76
e <- rnorm(800)
77
78
z <- rnorm(800)
79
80
c=1
81
Y <- c + 0.8*x1 + 1.2*x2 + 0.5*x3 + 1.5*x4 + 1.2*x5 + 0.5*x6 + 1.5*x7 + e
82
X <- cbind(matrix(1,800), x1,x2,x3,x4,x5,x6,x7)
83
84
ols <- function(M, Y , standar = T, Pvalue = T , instrumento = NULL, index = NULL){
85
86
87
if (standar & Pvalue & is.null(instrumento) & is.null(index)){
88
89
beta <- solve(t(M) %*% M) %*% (t(M) %*% Y)
90
91
y_est <- M %*% beta
92
n <- dim(M)[1]
93
k <- dim(M)[2] - 1
94
df <- n- k
95
sigma <- sum(sapply(Y - y_est , function(x) x ^ 2))/ df
96
97
Var <- sigma*solve(t(M) %*% M)
98
sd <- sapply(diag(Var) , sqrt)
99
100
t.est <- abs(beta/sd)
101
pvalue <-2*pt(t.est, df = df, lower.tail = FALSE) ## pt : t - student densidad
102
103
table <- data.frame(OLS= beta,
104
standar.error = sd, P.value = pvalue)
105
106
107
}
108
109
110
if ( !is.null(instrumento) & !is.null(index) ){
111
112
beta <- solve(t(M) %*% M) %*% (t(M) %*% Y)
113
114
index <- index + 1
115
116
Z <- X
117
Z[,index] <- z
118
119
beta_x <- solve(t(Z) %*% Z) %*% (t(Z) %*% X[,index])
120
121
x_est <- Z %*% beta_x
122
X[,index] <- x_est
123
124
beta_iv <- solve(t(X) %*% X) %*% (t(X) %*% Y)
125
126
table <- data.frame(OLS= beta,
127
OLS.IV = beta_iv)
128
129
130
131
return(table)
132
133