How to convert this code into a for-loop and have it automatically fill in the appropriate data in r?

Viewed 46

I created another post related to this here, but it caused a lot of confusion, so hopefully this post is clearer. FYI the code I initially wrote (but didn't do what I needed) for the loop is also in the link above if you want to see it.

goal

I'm trying to scrape all the competitor data from the IBJJF website. This includes each competitors division, gender, belt and weight. Although the stats only appear once at the top of the page, the below code will appropriately fill in the correct information for each competitor.

The problem

When this code is used in a for-loop, the loop does not automatically fill in the appropriate information for each competitor. For example, if the belt is black, I would like it to say black next to all competitors on that page. But I cannot figure out how to do that.

Question

How would you change this code into a loop so that the appropriate division, gender, belt, and weight is next to each competitor's name? Or if you were trying to capture all the data I mentioned from each page, how would you go about doing it?

library(rvest)
library(tidyverse)

MensUrl <- read_html('https://www.bjjcompsystem.com/tournaments/1869/categories/2053146')
  
## SCRAPE FIGHT INFO -------------------------------------------
# fight info
ageDivision <- MensUrl %>% 
  html_nodes('.category-title__age-division') %>% 
  html_text()
  
gender <- MensUrl %>% 
   html_nodes('.category-title__age-division+ .category-title__label') %>% 
  html_text()
  
belt <- MensUrl %>% 
  html_nodes('.category-title__label:nth-child(3)') %>% 
  html_text()
  
weight <-  MensUrl %>% 
  html_nodes('.category-title__label:nth-child(4)') %>% 
  html_text()
  
fightAndMat <- MensUrl %>% 
  html_nodes('.bracket-match-header__where , .bracket-match-header__fight') %>% 
  html_text()
  
date = MensUrl %>% 
  html_nodes('.bracket-match-header__when') %>% 
  html_text()
  
CompetitorNo = MensUrl %>% 
  html_nodes('.match-card__competitor-n') %>% 
  html_text()
  
name = MensUrl %>% 
  html_nodes('.match-card__competitor-description div:nth-child(1)') %>% 
  html_text()
  
gym = MensUrl %>% 
   html_nodes('.match-card__club-name') %>% 
   html_text()

#### create match df ####
matches = data.frame('division' = ageDivision,
                     'gender' = gender,
                     'belt' = belt,
                     'weight' = weight,
                     'fightAndMat' = fightAndMat,
                     'date' = date,
                     'competitor' = CompetitorNo,
                     'name' = name,
                     'gym' = gym)

This is what the above code produces when put in a data frame. I want the final result to look the same.

Original Data Frame

0 Answers
Related