/
fs_ary_basics.Rmd
298 lines (236 loc) · 7.49 KB
/
fs_ary_basics.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
---
title: "Basic Arrays Operations in R"
description: |
Generate N-dimensional array of NA values, label dimension elements.
Basic array operations in R, rep, head, tail, na, etc.
E notation.
Get N cuts from M points.
Convert numeric array to string array with positive and negative signs.
Calculation over array.
core:
- package: r
code: |
sum()
prod()
rep()
array(NA, dim=c(3, 3))
array(NA, dim=c(3, 3, 3))
dimnames(mn)[[3]] = paste0('k=', 0:4)
head()
tail()
na_if()
Re()
- package: purrr
code: |
reduce()
date: 2023-03-08
date_start: 2020-04-01
output:
pdf_document:
pandoc_args: '../../_output_kniti_pdf.yaml'
includes:
in_header: '../../preamble.tex'
html_document:
pandoc_args: '../../_output_kniti_html.yaml'
includes:
in_header: "../../hdga.html"
always_allow_html: true
urlcolor: blue
---
### Array Basics
```{r global_options, include = FALSE}
try(source("../../.Rprofile"))
```
`r text_shared_preamble_one`
`r text_shared_preamble_two`
`r text_shared_preamble_thr`
#### Sum and Product of Elements in Array
Product of Elements in Array.
```{r}
ar_a <- c(1,2,3)
ar_b <- c(1,2,3,4)
prod(ar_a)
prod(ar_b)
```
#### Multidimesional Arrays
##### Repeat one Number by the Size of an Array
```{r}
ar_a <- c(1,2,3)
ar_b <- c(1,2,3/1,2,3)
rep(0, length(ar_a))
```
##### Generate 2 Dimensional Array
First, we will generate an NaN matrix with 3 rows and 3 columnes.
```{r}
mt_x <- array(NA, dim=c(3, 3))
dim(mt_x)
print(mt_x)
```
Second, we will generate a matrix with 2 rows and four columns.
```{r}
mt_x <- array(c(1, 1.5, 0, 2, 0, 4, 0, 3), dim=c(2, 4))
dim(mt_x)
print(mt_x)
```
##### Generate 3 Dimensional Array
First, we will create a three dimensional array with the same data as what was used to create the 2-dimensional array on top.
```{r}
# Multidimensional Array
# 1 is r1c1t1, 1.5 in r2c1t1, 0 in r1c2t1, etc.
# Three dimensions, row first, column second, and tensor third
x <- array(c(1, 1.5, 0, 2, 0, 4, 0, 3), dim=c(2, 2, 2))
dim(x)
print(x)
```
Second, in the example below, we will generate a 3-dimensional array. The first dimension corresponds to different income levels, the second marital status, and the third the number of kids.We compute in the example below taxable income in 2008 given income levels given IRS rules.
```{r}
# A, Income Array
ar_income <- seq(0,200000,length.out=3)
# B. Exemptions and Deductions
fl_exemption <- 3500# exemption amount per household member
mt_deduction <- matrix(data=NA, nrow=2, ncol=5)# Marital-status and number of children-specific deduction
mt_deduction[1,1] <- 5450# Single filers
mt_deduction[1,2:5] <- 8000# Single filer with children
mt_deduction[2,] <- 10900# Married couples filing jointly
# C. Taxable Income
mn_taxable_income <- array(NA, dim=c(length(ar_income), 2, 5))
for (y in 1:length(ar_income)){
for (m in 1:2){
for (k in 0:4){
mn_taxable_income[y,m,k+1] <- ar_income[y]-fl_exemption*m-fl_exemption*k-mt_deduction[m,k+1]
}
}
}
# D. Name dimensions
dimnames(mn_taxable_income)[[1]] = paste0('income=', round(ar_income, 0))
dimnames(mn_taxable_income)[[2]] = paste0('married=', 0:1)
dimnames(mn_taxable_income)[[3]] = paste0('kids=', 0:4)
# E. Print
dim(mn_taxable_income)
print(mn_taxable_income)
```
#### Array Slicing
##### Get a Subset of Array Elements, N Cuts from M Points
There is an array with M elements, get N elements from the M elements.
First cut including the starting and ending points.
```{r}
it_M <- 5
it_N <- 4
ar_all_elements = seq(1,10,10)
```
##### Remove Elements of Array
Select elements with direct indexing, or with head and tail functions. Get the first two elements of three elements array.
```{r amto.array.fs_array_basics.slice.lastelement}
# Remove last element of array
vars.group.bydf <- c('23','dfa', 'wer')
vars.group.bydf[-length(vars.group.bydf)]
# Use the head function to remove last element
head(vars.group.bydf, -1)
head(vars.group.bydf, 2)
```
Get last two elements of array.
```{r}
# Remove first element of array
vars.group.bydf <- c('23','dfa', 'wer')
vars.group.bydf[2:length(vars.group.bydf)]
# Use Tail function
tail(vars.group.bydf, -1)
tail(vars.group.bydf, 2)
```
Select all except for the first and the last element of an array.
```{r}
# define array
ar_amin <- c(0, 0.25, 0.50, 0.75, 1)
# select without head and tail
tail(head(ar_amin, -1), -1)
```
Select the first and the last element of an array. The extreme values.
```{r}
# define array
ar_amin <- c(0, 0.25, 0.50, 0.75, 1)
# select head and tail
c(head(ar_amin, 1), tail(ar_amin, 1))
```
#### NA in Array
##### Check if NA is in Array
```{r amto.array.fs_array_basics.NA.check}
# Convert Inf and -Inf to NA
x <- c(1, -1, Inf, 10, -Inf)
na_if(na_if(x, -Inf), Inf)
```
#### Complex Number
Handling numbers with real and imaginary components. Two separate issues, given an array of numbers that includes real as well as imaginary numbers, keep subset that only has real components. Additionally, for the same array, generate an equal length version of the array that includes the real components of all numbers.
Define complex numbers.
```{r}
# Define a complex number
cx_number_a <- 0+0.0460246857561777i
# Define another complex number
cx_number_b <- complex(real = 0.02560982, imaginary = 0.0460246857561777)
# An array of numbers some of which are complex
ar_cx_number <- c(0.02560982+0.000000000i, 0.00000000+0.044895305i,
0.00000000+0.009153429i, 0.05462045+0.000000000i,
0.00000000+0.001198538i, 0.00000000+0.019267050i)
```
Extract real components from a complex array.
```{r}
# equi-length real component
ar_fl_number_re <- Re(ar_cx_number)
print(ar_fl_number_re)
# equi-length img component
ar_fl_number_im <- Im(ar_cx_number)
print(ar_fl_number_im)
```
Keep only real elements of array.
```{r}
# subset of array that is real
ar_fl_number_re_subset <- Re(ar_cx_number[Re(ar_cx_number)!=0])
print(ar_fl_number_re_subset)
```
#### Number Formatting
##### e notation
1. Case one: *1.149946e+00*
+ this is approximately: 1.14995
2. Case two: *9.048038e-01*
+ this is approximately: 0.90480
3. Case three: *9.048038e-01*
+ this is approximately: 0.90480
#### String Conversions
##### Add Positive and Negative Sign in Front of Values
We have a sequence of integers, some positive and some negative. We convert this into a string array, and append positive sign in front of positive values.
```{r}
# An array of integers
ar_it_vals <- seq(-5, 5, by = 1)
# Add positive sign in front of positive and zero elements
st_it_vals <- paste0(ar_it_vals)
st_it_vals[ar_it_vals>0] <- paste0("+", st_it_vals[ar_it_vals>0])
st_it_vals[ar_it_vals==0] <- paste0("±", st_it_vals[ar_it_vals==0])
# Display
print(st_it_vals)
```
#### Basic array calculations
First, we demonstrate how purrr::reduce() works with a simple summation example. We use the addition operator.
```{r}
# Using R pipe operator
# 1 + 2 + 3 = 6
fl_sum <- 1:3 |> purrr::reduce(`+`)
print(fl_sum)
```
Second, what if there is an NA value? NA will be ignored, we will write a custom function. The custom function, to work with reduce, should be such that it is "a binary function that takes two values and returns a single value".
```{r}
# define sum function that ignores NA
sum_ignore_na <- function(x,y) {
if (!is.na(x) && !is.na(y)) {
x + y
} else if (is.na(x)) {
y
} else if (is.na(y)) {
x
} else {
NA
}
}
# Using R pipe operator
# 1 + 10 + 1 = 12
fl_sum <- c(1, 10, NA, 1) |> purrr::reduce(sum_ignore_na)
print(fl_sum)
```