-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathR
57 lines (44 loc) · 1.82 KB
/
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
no claim that any of this is original code
# lifted in learning exercises over time
# the RStudio editor will code fold the examples below
# Read Excel, Manipulate Rows/Columns, Write Excel ------------------------------------------------
library(dplyr)
library(readxl)
library(writexl)
library(lubridate)
library(stringr)
XLSX_FILE <- "Planets"
planets <- read_excel(paste0(XLSX_FILE,".xlsx"), sheet = "List of Planets")
# add a column with the row number
planets <- mutate(planets, RowNum = row_number())
# move RowNum column to the far left
planets <- select(planets, RowNum, everything())
# rename a column
names(planets)[names(planets) == 'RowNum'] <- 'Row Number'
# a good way to rename lots of columns
# omitting a column will remove it
planets <- rename(planets,
RowNum = "Row Number",
Planet = Planet,
Distance = "Distance (AU)",
Revolution = Revolution,
Rotation = Rotation,
Mass = Mass,
Diameter = Diameter,
Satellites = Satellites)
# remove RowNum column
planets <- subset(planets, select = -c(RowNum))
# remove the Uranus row
planets <- filter(planets, Planet != "Uranus")
# getting and setting a valume in a dataframe
saturn_mass <- as.numeric(planets[which(planets$Planet == "Saturn"), "Mass"])
planets[which(planets$Planet == "Saturn"), "Mass"] <- saturn_mass
# create Excel filename with date/time stamp at the end
filename <- paste(XLSX_FILE, now())
# remove the seconds and replace the colon in now()
filename <- str_sub(str_replace_all(filename,":",""),-100,-3)
filename <- paste0(filename,".xlsx")
# can save multiple worksheets
worksheets <- list("List of Planets" = planets,
"Copy of List of Planets" = planets)
tmp <- writexl::write_xlsx(worksheets, filename)