-
Notifications
You must be signed in to change notification settings - Fork 0
/
_003_accessing.R
69 lines (51 loc) · 1.44 KB
/
_003_accessing.R
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
# Filename: _003_accessing.R
# Title: Accessing value from data structures
# Author: Raghava | GitHub : @raghavtwenty
# Date Created: June 20, 2023 | Last Updated: May 24, 2024
# Language: R | Version: 4.4.0
# Vector
my_vector <- c(10, 20, 30, 40, 50)
print(my_vector[1]) # In R index starts from 1
print(my_vector[c(1,3)])
# List
my_list <- list(
name = "Raghav",
age = 20,
scores = c(91, 95)
)
# Access by name
print(my_list$name)
# Access by index
print(my_list[[2]])
# Access nested elements
print(my_list$scores[1])
# Data Frames
my_df <- data.frame(
string = c("Hello", "Good"),
length = c(5,4),
starting_letter = c("H", "G")
)
# Access by column name using $
print(my_df$string)
# Access by column name using double square brackets
print(my_df[["length"]])
# Access by column index
print(my_df[, 1]) # First column
print(my_df[, "length"]) # Column named "length"
# Access the first row
print(my_df[1, ])
# Access multiple rows
print(my_df[1:2, ])
# Access specific cells
print(my_df[1, 2]) # First row, second column
print(my_df[2, "starting_letter"]) # Second row, column "starting_letter"
# Dates and Times
today <- Sys.Date()
# Get the year, month, and day from a date
year <- format(today, "%Y")
month <- format(today, "%m")
day <- format(today, "%d")
print(paste("Year:", year, "Month:", month, "Day:", day))
# Format the date in different ways
formatted_date <- format(today, "%B %d, %Y")
print(formatted_date)