I have some data from which I can create a table in the RStudio console using
#Open latest file
#get a vector of all filenames 
files <- list.files(path="MYFILEPATH",pattern="files.xls",full.names = TRUE,recursive = TRUE)
#get the directory names of these (for grouping)
dirs <- dirname(files)
#find the last file in each directory (i.e. latest modified time)
lastfiles <- tapply(files,dirs,function(v) v[which.max(file.mtime(v))])
File_List <- file.info(list.files("//MYFILEPATH", full.names = T))
Path_Of_Interest <- rownames(File_List)[which.max(File_List$mtime)]
library(readxl)
MyData <- read_excel(Path_Of_Interest,
    col_types = c("numeric", "skip", "skip", 
        "skip", "skip", "numeric", "skip", 
        "skip", "skip", "skip", "skip", "skip", 
        "skip", "skip", "text", "text", "skip", 
        "skip", "skip", "skip", "skip", "skip", 
        "skip", "skip", "skip", "skip", "date", 
        "date", "skip", "skip", "skip", "skip", 
        "skip", "skip", "skip", "skip", "skip", 
        "skip", "skip", "skip", "skip", "skip", 
        "skip", "skip", "skip", "skip"))
#Rename columns
MyData <- MyData %>%
rename(Age = "Age (Years)", Area = "Preferred Area", SeniorArea = "Preferred Senior Area", SaleDate = "Sale Date", ReturnDate = "Return Date")
#Group Age Column
MyData["Age"] = cut(MyData$Age, c(0, 17, Inf), c("0-17", "18+"), include.lowest=TRUE)
#Filter to most recent data only
MyData %>%
select(Age, Area, SaleDate) %>%
filter(SaleDate >= as.Date("2021-10-25") & SaleDate <= as.Date("2021-10-31"))
#Create table
table(MyData$Area, MyData$Age)
Raw data example here:
| ID | Area | Age | 
|---|---|---|
| 1 | AreaA | 0-17 | 
| 2 | AreaA | 0-17 | 
| 3 | AreaB | 18+ | 
| 4 | AreaB | 18+ | 
| 5 | AreaB | 0-17 | 
The output in the console looks like how I would like it to look, similar to below:
| Area | 0-17 | 18+ | 
|---|---|---|
| AreaA | 310 | 405 | 
| AreaB | 210 | 401 | 
However when I try to create an object out of this table (in order to merge it with another later) and then view the object I get a table like the below (not all rows included but you can see the column names)
| Var1 | Var2 | Freq | 
|---|---|---|
| AreaA | 0-17 | 310 | 
| AreaB | 0-17 | 210 | 
Can anyone please advise how to create the object to match format similar to the first table above for use in other things?
Basically I just need to be able to create an object which is the equivalent of an Excel pivot table with 'Area' for columns and count of 'Age' for rows.
Thank you!
