在R DataFrame中基于国别列筛选提取意大利球队
Extract Italian Teams from Your Tibble
Got it, let's work through this. You need to pull all teams that are from Italy (marked by "ITA" in either hcountry or vcountry). Here are a couple of straightforward ways to do this in R:
Option 1: Using Tidyverse (dplyr + tidyr)
This method is great if you're already working with tibbles and prefer a pipe-based workflow:
library(dplyr) library(tidyr) library(stringr) # Optional, for case standardization # Extract and clean the Italian teams italian_teams <- df %>% # Reshape data to get one team per row pivot_longer( cols = c(home, visitor), names_to = "team_role", values_to = "team_name", names_pattern = "(home|visitor)" ) %>% # Match each team to its country mutate(team_country = case_when( team_role == "home" ~ hcountry, team_role == "visitor" ~ vcountry )) %>% # Keep only Italian teams filter(team_country == "ITA") %>% # Optional: Standardize case (fixes "Milan" vs "MILAN") mutate(team_name = str_to_title(team_name)) %>% # Pull just the team names as a vector pull(team_name) # View the result italian_teams
Running this will give you:
[1] "Milan" "Milan" "Juventus"
Option 2: Base R (No Extra Packages)
If you prefer sticking to base R, this simple approach works too:
# Get home teams from Italy home_italian <- df$home[df$hcountry == "ITA"] # Get visitor teams from Italy visitor_italian <- df$visitor[df$vcountry == "ITA"] # Combine into a single vector italian_teams <- c(home_italian, visitor_italian) # Optional: Standardize case italian_teams <- stringr::str_to_title(italian_teams) # Or use tolower()/toupper() italian_teams
Both methods will get you the list of Italian teams you need. The tidyverse approach is more flexible if you want to do additional data cleaning or manipulation later!
内容的提问来源于stack exchange,提问作者joe borg
相关产品推荐
相关产品推荐

