-
Notifications
You must be signed in to change notification settings - Fork 0
/
reshape.R
73 lines (63 loc) · 2.21 KB
/
reshape.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
70
71
72
73
# loading libraries
library(here)
library(dplyr)
library(tidyr)
library(readr)
# library(jsonlite)
# function for modifying colnames
reverse_string <- function(x) {
paste0("item_", trimws(paste(sub('.*_', '', x), sub('_.*', '', x), sep = '.')))
}
# importing data
df <- read_csv(here("data/wide.csv"))
relic <- read_csv(here("data/relic.csv"))
src <- read_csv(here("data/sources.csv"))
# removing useless columns
src <- src %>%
rename(source = title,
source_slug = slug) %>%
select(source, source_slug, list, list_id)
rlc <- relic %>%
select(-subject_id)
# reshaping
long <- df %>%
rename_with(reverse_string, 8:ncol(df)) %>% #secondo argomento debole, ma per ora funziona
select(-info_url, -info, -info_title, -subject_description) %>%
pivot_longer(cols = starts_with("item"),
names_to = c(".value", "field"), names_sep = "_") %>%
separate(field, into = c("type", "list"), sep = "\\.") %>%
spread(type, item) %>%
select(-list) %>%
left_join(rlc, ., by = "subject") %>%
left_join(., src, by = "source", ) %>%
filter(endorsement != "NA") %>%
mutate(id = row_number()) %>%
select(id, category, category_id, subject, subject_slug, subject_id, source, source_slug, list, list_id, endorsement, description)
# exporting csv
# write.csv(long, here("data/items.csv"), na = "", fileEncoding = "UTF-8")
write_csv(long, here("data/items.csv"), na = "")
print("Reshaping completed! items.csv created.")
# generating glossary.csv
df %>%
select(subject_id, subject, subject_slug, info_url, info, info_title, subject_description) %>%
rename(
id = subject_id,
url = info_url,
source = info,
title = info_title,
slug = subject_slug,
description = subject_description) %>%
write_csv(., here("data/glossary.csv"), na = "")
print("glossary.csv created")
# delete temp file
file.remove(here("data/wide.csv"))
print("wide.csv deleted")
# generating json
# files <- list.files(path="data/", pattern="*.csv", full.names=TRUE, recursive=FALSE)
#
# lapply(files, function(x) {
# read.csv(x, fileEncoding = "UTF-8") %>%
# toJSON(., encoding = "UTF-8") %>%
# write(., gsub(".csv", ".json", x))
# })
# print("csv2json completed")