-
Notifications
You must be signed in to change notification settings - Fork 1
/
.Rhistory
512 lines (512 loc) · 17.3 KB
/
.Rhistory
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
model_results <- fit_model(train_data, test_data)
model_results
# Function to perform a simulation and store outputs
run_simulation <- function(num_simulations) {
simulation_results <- list()
for (i in 1:num_simulations) {
# Perform simulation
simulated_data <- rnorm(100)
# Store simulation outputs in the list
simulation_results[[paste0("simulation_", i)]] <- simulated_data
}
return(simulation_results)
}
# Usage of the function and storing outputs in a list
simulations <- run_simulation(5)
simulations
head(simulations)
# Creating a data frame manually
names <- c("Alice", "Bob", "Charlie", "David")
ages <- c(25, 30, 28, 35)
scores <- c(88, 92, 75, 80)
# Creating a data frame using the data
df <- data.frame(Name = names, Age = ages, Score = scores)
print(df)
# Sample data frame creation
student_id <- 1:5
student_names <- c("Alice", "Bob", "Charlie", "David", "Eva")
ages <- c(20, 22, 21, 23, 20)
scores <- c(85, 90, 78, 92, 88)
students <- data.frame(ID = student_id, Name = student_names, Age = ages, Score = scores)
# Accessing the 'Name' column using $
students$Name
# Accessing the 'Age' column using double brackets [[ ]]
students[["Age"]]
students["Age"]
students["Age"]
students[["Age"]]
# Accessing a single element in row 3, column 2
students[3, 2]
# Accessing a single element by row and column names
students["3", "Name"]
# Selecting rows where Age is greater than 25 and Score is above 80
students[students$Age > 25 & students$Score > 80, ]
students
students
# Selecting rows where Age is greater than 25 and Score is above 80
students[students$Age > 20 & students$Score > 80, ]
# Creating a tibble from a data frame
library(tibble)
# Creating a tibble
my_tibble <- tibble(
column1 = c(1, 2, 3),
column2 = c("A", "B", "C")
)
my_tibble
# Creating a data frame with sequences and vectors
names <- c("Alice", "Bob", "Charlie", "David")
ages <- seq(from = 25, to = 35, by = 5)
scores <- sample(70:100, 4, replace = TRUE)
# Creating a data frame using the data generated
df <- data.frame(Name = names, Age = ages, Score = scores)
names
ages
ages <- seq(from = 20, to = 35, by = 5)
ages
scores
# Creating a data frame with sequences and vectors
names <- c("Alice", "Bob", "Charlie", "David")
ages <- seq(from = 20, to = 35, by = 5)
scores <- sample(70:100, 4, replace = TRUE)
# Creating a data frame using the data generated
df <- data.frame(Name = names, Age = ages, Score = scores)
print(df)
rm(list=ls())
# Creating a factor for educational levels
education_levels <- c("High School", "Graduate", "Undergraduate", "High School", "Undergraduate")
education_factor <- factor(education_levels)
# Checking unique values within the factor
unique(education_factor)
# Sample data as a vector
gender <- c("Male", "Female", "Male", "Male", "Female")
# Converting to factor
gender_factor <- factor(gender)
# Checking levels
levels(gender_factor)
# Sample data as a vector
gender <- c("Male", "Female", "Male", "Male", "Female")
# Converting to factor
gender_factor <- factor(gender)
# Checking levels
levels(gender_factor)
# Checking unique values within the factor
unique(gender_factor)
# Simulated data for a model
education <- c("High School", "Graduate", "Undergraduate", "High School", "Undergraduate")
income <- c("Low", "High", "Medium", "Low", "High")
response <- c(20, 35, 28, 18, 40)
# Converting categorical variables to factors for modeling
education_factor <- factor(education)
income_factor <- factor(income)
# Linear model
model <- lm(response ~ education_factor + income_factor)
summary(model)
categories <- sample(c("Electronics", "Clothing", "Food"),
size = 20 ,
replace = TRUE)
categories
category_factor <- factor(categories)
# Creating a bar plot with factors
ggplot() +
geom_bar(aes(x = category_factor, fill = category_factor)) +
labs(title = "Distribution of Product Categories", x = "Category", y = "Count")
# Creating a bar plot with factors
ggplot2::ggplot() +
geom_bar(aes(x = category_factor, fill = category_factor)) +
labs(title = "Distribution of Product Categories", x = "Category", y = "Count")
# Creating a bar plot with factors
ggplot2::ggplot(aes(x = category_factor, fill = category_factor)) +
geom_bar() +
labs(title = "Distribution of Product Categories", x = "Category", y = "Count")
category_factor
# Creating a bar plot with factors using ggplot2
library(ggplot2)
# Creating a data frame for ggplot
data <- data.frame(category = category_factor)
# Creating a bar plot
ggplot(data, aes(x = category, fill = category)) +
geom_bar() +
labs(title = "Distribution of Product Categories", x = "Category", y = "Count")
# Simulated data for spending behavior
spending <- c(200, 350, 280, 180, 400)
income_levels <- c("Low", "High", "Medium", "Low", "High")
education_levels <- c("High School", "Graduate", "Undergraduate", "Graduate", "Undergraduate")
# Creating factor variables for income and education
income_factor <- factor(income_levels)
education_factor <- factor(education_levels)
# Linear model with both income and education as factor variables
model <- lm(spending ~ income_factor + education_factor)
summary(model)
model
View(model)
# Simulated data for spending behavior
spending <- c(200, 350, 280, 180, 400)
income_levels <- c("Low", "High", "Medium", "Low", "High")
education_levels <- c("High School", "Graduate", "Undergraduate", "Graduate", "Undergraduate")
# Creating factor variables for income and education
income_factor <- factor(income_levels)
education_factor <- factor(education_levels)
# Linear model with both income and education as factor variables
model <- lm(spending ~ income_factor + education_factor)
summary(model)
spending <- runif(n, min = 100, max = 600)
# Simulated data for spending behavior
n <- 100
spending <- runif(n, min = 100, max = 600)
spending
income_levels <- sample(c("Low", "High", "Medium"), size = n, replace = TRUE)
education_levels <- sample(c("High School", "Graduate", "Undergraduate"),
size = n,
replace = TRUE)
# Creating factor variables for income and education
income_factor <- factor(income_levels)
education_factor <- factor(education_levels)
# Linear model with both income and education as factor variables
model <- lm(spending ~ income_factor + education_factor)
summary(model)
rm(list=ls())
library(microbenchmark)
num_list <- list(a = 1:1000, b = 1001:2000, c = 2001:3000)
benchmark_results <- microbenchmark(
apply_sum = apply(num_list, 2, sum),
sapply_sum = sapply(num_list, sum),
lapply_sum = lapply(num_list, sum),
map_sum = map_dbl(num_list, sum),
times = 100
)
View(num_list)
num_list <- list(a = 1:3, b = 4:6, c = 7:9)
custom_function <- function(x) sum(x) * 2
result_list <- lapply(num_list, custom_function)
print(result_list)
word_list <- list("apple", "banana", "orange", "grape")
vowel_list <- lapply(word_list, function(word) grep("[aeiou]", strsplit(word, "")[[1]], value = TRUE))
print(vowel_list)
library(purrr)
num_list <- list(a = 1:3, b = 4:6, c = 7:9)
mapped_results <- map(num_list, ~ .x^2)
print(mapped_results)
text_list <- list("hello", "world", "R", "programming")
string_lengths <- map(text_list, nchar)
print(string_lengths)
library(microbenchmark)
# 1000x1000 boyutunda bir matris oluşturalım
matris_data <- matrix(rnorm(1000000), nrow = 1000)
# Toplamı hesaplamak için apply() fonksiyonunu kullanalım
benchmark_results <- microbenchmark(
apply_sum = apply(matris_data, 2, sum),
sapply_sum = sapply(matris_data, sum),
lapply_sum = lapply(matris_data, sum),
map_sum = map_dbl(as.list(matris_data), sum), # map fonksiyonu için listeye çevirmemiz gerekiyor
times = 100
)
print(benchmark_results)
View(matris_data)
# Create a 100 x 100 matrix
matrix_data <- matrix(rnorm(10000), nrow = 100)
# Use apply() function to compute the sum for each column
benchmark_results <- microbenchmark(
apply_sum = apply(matrix_data, 2, sum),
sapply_sum = sapply(matrix_data, sum),
lapply_sum = lapply(matrix_data, sum),
map_sum = map_dbl(as.list(matrix_data), sum), # We need to convert the matrix to a list for the map function
times = 100
)
print(benchmark_results)
rm(list=ls())
library(microbenchmark)
library(tidyr)
sales_data <- data.frame(
product = c("A", "B", "C"),
Jan = c(500, 600, 300),
Feb = c(450, 700, 320),
Mar = c(520, 640, 310)
)
sales_long <- pivot_longer(sales_data, cols = Jan:Mar,
names_to = "month", values_to = "sales")
sales_long
sales_wide <- pivot_wider(sales_long, names_from = month, values_from = sales)
sales_wide
sales_long <- pivot_longer(sales_data, cols = Jan:Feb,
names_to = "month", values_to = "sales",
values_drop_na = TRUE)
sales_long
sales_data <- data.frame(
product = c("A", "A", "B", "B", "C", "C"),
region = c("North", "South", "North", "South", "North", "South"),
Jan = c(500, NA, 600, 580, 300, 350),
Feb = c(450, 490, NA, 700, 320, 400)
)
sales_data
sales_long <- pivot_longer(sales_data, cols = Jan:Feb,
names_to = "month", values_to = "sales",
values_drop_na = TRUE)
sales_long
# Gerekli paketleri yükle
library(tidyr)
library(ggplot2)
# Veri setini oluştur
sales_data <- data.frame(
product = c("A", "B", "C"),
Jan = c(500, 600, 300),
Feb = c(450, 700, 320),
Mar = c(520, 640, 310)
)
# Veriyi uzun formata dönüştür
sales_long <- pivot_longer(sales_data, cols = Jan:Mar,
names_to = "month", values_to = "sales")
# Çubuk grafiği oluştur
ggplot(sales_long, aes(x = month, y = sales, fill = product)) +
geom_bar(stat = "identity", position = "dodge") +
labs(title = "Sales Data: Long Format Example", x = "Month", y = "Sales") +
theme_minimal() +
theme(plot.title = element_text(hjust = 0.5))
Sys.info()
Sys.getlocale()
Sys.getenv()
Sys.getlocale()
sessionInfo()
source("set_locale.R")
file.path("~", ".Rprofile")
help(Startup)
R.home(component = "home")
readRenviron("~/.Renviron")
date_example <- as.Date("2024-09-21")
date_example <- as.Date("2024-09-21")
date_example
datetime_example <- as.POSIXct("2024-09-21 14:45:00", tz = "UTC")
datetime_example
library(lubridate)
# Convert date strings to Date objects
date1 <- ymd("2024-09-21")
date1
date2 <- dmy("21-09-2024")
date2
# Convert to date-time
datetime1 <- ymd_hms("2024-09-21 14:45:00", tz = "UTC")
datetime1
datetime2 <- mdy_hms("09/21/2024 02:45:00 PM", tz = "America/New_York")
datetime2
#| message: false
library(lubridate)
# Convert date strings to Date objects
date1 <- ymd("2024-09-21")
date1
date2 <- dmy("21-09-2024")
date2
# Convert to date-time
datetime1 <- ymd_hms("2024-09-21 14:45:00", tz = "UTC")
datetime1
datetime2 <- mdy_hms("09/21/2024 02:45:00 PM", tz = "America/New_York")
datetime2
library(lubridate)
# Parsing a date-time object
datetime <- ymd_hms("2024-09-30 14:45:30")
# Extracting components
year(datetime)
month(datetime)
day(datetime)
hour(datetime)
minute(datetime)
second(datetime)
# Extracting weekday
wday(datetime)
wday(datetime, label = TRUE)
wday(datetime, label = TRUE, abbr = FALSE)
# Extracting month by name
month(datetime, label = TRUE, abbr = FALSE)
# Changing the month by name
month(datetime) <- 7
datetime
# Set a different time zone
datetime_tz <- with_tz(datetime, "America/New_York")
datetime_tz
# Extract hour in the new time zone
hour(datetime_tz) # Output: 4 (converted from UTC to EDT)
# Creating a duration of 1 day
one_day <- ddays(1)
one_day
# Duration of 2 hours and 30 minutes
duration_time <- dhours(2) + dminutes(30)
duration_time
# Adding a duration to a date
start_date <- ymd("2024-09-21")
end_date <- start_date + ddays(7)
end_date
# Creating a period of 2 years, 3 months, and 10 days
my_period <- years(2) + months(3) + days(10)
my_period # Output: "2y 3m 10d"
# Adding the period to a date
new_date <- start_date + my_period
new_date # Output: "2026-12-01"
start_date
# Adding a duration to a date
start_date <- ymd("2024-09-30")
# Adding the period to a date
new_date <- start_date + my_period
new_date
# Creating an interval between two dates
start_date <- ymd("2024-01-01")
end_date <- ymd("2024-12-31")
time_interval <- interval(start_date, end_date)
time_interval
# Checking how many days are in the interval
as.duration(time_interval)
# Creating an interval and calculating the duration
interval_span <- interval(ymd("2024-09-01"), ymd("2024-12-01"))
interval_duration <- as.duration(interval_span) # Duration in seconds
# Adjusting the interval by adding a period
extended_interval <- interval_span + months(1)
interval_span
interval_duration
extended_interval
# Adjusting the interval by adding a period
extended_interval <- interval_span + months(1)
# Create an interval between two dates
start_date <- ymd("2024-09-01")
end_date <- ymd("2024-12-01")
interval_span <- interval(start_date, end_date)
# Extend the end date by 1 month
new_end_date <- end_date + months(1)
# Create a new interval with the updated end date
extended_interval <- interval(start_date, new_end_date)
# Display the extended interval
extended_interval # Output: "2024-09-01 UTC--2025-01-01 UTC"
# Example of irregular dates (missing some days)
irregular_dates <- c(ymd("2023-01-01"), ymd("2023-01-02"), ymd("2023-01-05"),
ymd("2023-01-07"), ymd("2023-01-10"))
# Create a dataset with missing dates
irregular_data <- data.frame(
date = irregular_dates,
value = runif(5, min = 100, max = 200)
)
# Complete the time series by filling missing dates
complete_dates <- data.frame(
date = seq(min(irregular_data$date), max(irregular_data$date), by = "day")
)
# Join the original data with the complete sequence of dates
complete_data <- merge(complete_dates, irregular_data, by = "date", all.x = TRUE)
# View the completed data with missing values
complete_data
# Converting a ts object to a data frame with dates
ts_data <- ts(sales_data, start = c(2020, 1), frequency = 12)
# Create a data frame from the ts object
df_ts <- data.frame(
date = seq(ymd("2020-01-01"), by = "month", length.out = length(ts_data)),
sales = as.numeric(ts_data)
)
# Extract year and month using lubridate
df_ts <- df_ts %>%
mutate(year = year(date), month = month(date))
library(dplyr)
#| message: false
library(dplyr)
# Sample dataset: daily values over one month
set.seed(123)
time_series_data <- data.frame(
date = seq(ymd("2023-01-01"), by = "day", length.out = 30),
value = runif(30, min = 50, max = 150)
)
# Aggregating the data by week
weekly_data <- time_series_data %>%
mutate(week = floor_date(date, "week")) %>%
group_by(week) %>%
summarize(weekly_avg = mean(value))
# View the aggregated data
weekly_data
# Converting a ts object to a data frame with dates
ts_data <- ts(sales_data, start = c(2020, 1), frequency = 12)
# Create a data frame from the ts object
df_ts <- data.frame(
date = seq(ymd("2020-01-01"), by = "month", length.out = length(ts_data)),
sales = as.numeric(ts_data)
)
# Extract year and month using lubridate
df_ts <- df_ts %>%
mutate(year = year(date), month = month(date))
# View the data with extracted components
df_ts
sales_data
View(sales_data)
# Sample data: monthly sales from 2020 to 2022
sales_data <- c(100, 120, 150, 170, 160, 130, 140, 180, 200, 190, 210, 220,
230, 250, 270, 300, 280, 260, 290, 310, 330, 340, 350, 360)
# Creating a time series object (monthly data starting from Jan 2020)
ts_sales <- ts(sales_data, start = c(2020, 1), frequency = 12)
ts_sales
# Convert time series to a data frame with date information
sales_df <- data.frame(
date = seq(ymd("2020-01-01"), by = "month", length.out = length(ts_sales)),
sales = as.numeric(ts_sales)
)
# Display the resulting data frame
sales_df
# Generate a sequence of daily dates
daily_dates <- seq(ymd("2023-01-01"), by = "day", length.out = 30)
# Create a sample dataset with random values for each day
daily_data <- data.frame(
date = daily_dates,
value = runif(30, min = 100, max = 200)
)
# View the first few rows of the dataset
head(daily_data)
#| message: false
library(dplyr)
# Sample dataset: daily values over one month
set.seed(123)
time_series_data <- data.frame(
date = seq(ymd("2023-01-01"), by = "day", length.out = 30),
value = runif(30, min = 50, max = 150)
)
# Aggregating the data by week
weekly_data <- time_series_data |>
mutate(week = floor_date(date, "week")) |>
group_by(week) |>
summarize(weekly_avg = mean(value))
# View the aggregated data
weekly_data
# Example of irregular dates (missing some days)
irregular_dates <- c(ymd("2023-01-01"), ymd("2023-01-02"), ymd("2023-01-05"),
ymd("2023-01-07"), ymd("2023-01-10"))
# Create a dataset with missing dates
irregular_data <- data.frame(
date = irregular_dates,
value = runif(5, min = 100, max = 200)
)
# Complete the time series by filling missing dates
complete_dates <- data.frame(
date = seq(min(irregular_data$date), max(irregular_data$date), by = "day")
)
# Join the original data with the complete sequence of dates
complete_data <- merge(complete_dates, irregular_data, by = "date", all.x = TRUE)
# View the completed data with missing values
complete_data
# Converting a ts object to a data frame with dates
ts_data <- ts(sales_data, start = c(2020, 1), frequency = 12)
# Create a data frame from the ts object
df_ts <- data.frame(
date = seq(ymd("2020-01-01"), by = "month", length.out = length(ts_data)),
sales = as.numeric(ts_data)
)
# Extract year and month using lubridate
df_ts <- df_ts %>%
mutate(year = year(date), month = month(date))
# View the data with extracted components
df_ts
#| eval: false
parse_date_time(x, orders, tz = "UTC", quiet = FALSE)
# Example date-time strings in various formats
dates <- c("2024-01-15", "01/16/2024", "March 17, 2024", "18-04-2024")
# Parse the dates using parse_date_time
parsed_dates <- parse_date_time(dates, orders = c("ymd", "mdy", "dmy", "B d, Y"))
# Display the parsed dates
parsed_dates
hours(3)
# Define task durations
task_duration <- hours(3) # Each task takes 3 hours
start_time <- ymd_hms("2024-01-01 09:00:00")
# Schedule three tasks
schedule <- start_time + task_duration * 0:2
# Display the schedule for tasks
schedule
rm(list=ls())