tpemartin / 110-2-R

The class repo for 110-2 Programming for Data Science
0 stars 3 forks source link

Animal Shelter Data: for loop application #15

Open tpemartin opened 2 years ago

tpemartin commented 2 years ago
animalShelterData <- 
  jsonlite::fromJSON("https://www.dropbox.com/s/jew0opl6emhnw8o/animal_shelter.json?dl=1")
animalShelterData |> View()

Christy's version

# result saving container 
allPagesData <- vector("list", 148)
for(.y in 1:148)
{
  {
  clean_animal_data2<-list()

  for(.x in 1:8)
  {
  clean_animal_data2[[.x]] <- list()
  clean_animal_data2[[.x]]$IDnumber<- animalShelterData[[.y]]$description[[.x]][[2]]
  clean_animal_data2[[.x]]$Cage<-animalShelterData[[.y]]$description[[.x]][[1]]
  clean_animal_data2[[.x]]$Feature$毛色<- animalShelterData[[.y]]$description[[.x]][[7]]
  clean_animal_data2[[.x]]$Feature$毛長<- animalShelterData[[.y]]$description[[.x]][[8]]
  clean_animal_data2[[.x]]$Feature$體型<-animalShelterData[[.y]]$description[[.x]][[9]]
  clean_animal_data2[[.x]]$Feature$品種<-animalShelterData[[.y]]$description[[.x]][[10]]
  clean_animal_data2[[.x]]$Feature$性別<-animalShelterData[[.y]]$description[[.x]][[11]]
  clean_animal_data2[[.x]]$Feature$年齡<-animalShelterData[[.y]]$description[[.x]][[12]]
  clean_animal_data2[[.x]]$Feature$特徵<-animalShelterData[[.y]]$description[[.x]][[13]]
  clean_animal_data2[[.x]]$Located$位置<-animalShelterData[[.y]]$description[[.x]][[14]]
  clean_animal_data2[[.x]]$Located$電話<-animalShelterData[[.y]]$description[[.x]][[15]]
  clean_animal_data2[[.x]]$Located$開放時間<-animalShelterData[[.y]]$description[[.x]][[16]]
  }

  clean_animal_data2
  } -> allPagesData[[.y]]
}
unlist(allPagesData, recursive = FALSE) -> allData

Martin's version

# declare a data list
clean_animal_data2 <- list()

for(.x in 1:8)
{
  # retrieve one animal's description
  oneDescription = animalShelterData[[1]]$description[[.x]] # page 1 animal 3

  # get one observation from one animal's description
  oneObservation <- {
  oneObservation<-list()
  oneObservation$IDnumber<- oneDescription[[2]]
  oneObservation$Cage<-oneDescription[[1]]
  features <- list()
  features$毛色<- oneDescription[[7]]
  features$毛長<- oneDescription[[8]]
  features$體型<-oneDescription[[9]]
  features$品種<-oneDescription[[10]]
  features$性別<-oneDescription[[11]]
  features$年齡<-oneDescription[[12]]
  features$特徵<-oneDescription[[13]]
  oneObservation$Feature <- list(features)
  locations <- list()
  locations$位置<-oneDescription[[14]]
  locations$電話<-oneDescription[[15]]
  locations$開放時間<-oneDescription[[16]]
  oneObservation$Located <- list(locations)
  oneObservation
}

  # save this observation to data list
  clean_animal_data2[[.x]] <- oneObservation
  }

a_ijk xyz

clean_animal_data2 |> purrr::transpose() -> list_fbf
list2DF(list_fbf) -> df_animal
View(df_animal)