如何用函数或循环在DataFrame中按条件替换巴哈马的大洲值?
Hey there! Let's work through how to update the continent for "Bahamas" to "South America" in your DataFrame. I'll cover a few approaches—including a function-based method and a loop, since you mentioned those options.
First, let's recreate your sample DataFrame to test with:
# Sample DataFrame matching your input df <- data.frame( country = c("Taiwan", "New Zealand", "Bulgaria", "Bahamas", "Serbia", "Tajikistan", "Southern Sub-Saharan Africa", "Cameroon", "Indonesia", "Democratic Republic of Congo"), continent = c("Asia", "Oceania", "Europe", "Americas", "Europe", "Asia", NA, "Africa", "Asia", "Africa"), stringsAsFactors = FALSE )
Approach 1: Vectorized Function (Most Efficient)
Using dplyr (part of the tidyverse) is a clean, function-based way to handle this. We'll use mutate() with ifelse() to target the specific row:
library(dplyr) # Update the continent value df_updated <- df %>% mutate(continent = ifelse(country == "Bahamas", "South America", continent))
This checks every row: if the country is "Bahamas", it replaces the continent value; otherwise, it keeps the original entry. Vectorized operations like this are faster than loops for most datasets.
Approach 2: Base R Direct Indexing
If you prefer not to use tidyverse packages, you can directly target the row with base R:
# Modify the value in-place df$continent[df$country == "Bahamas"] <- "South America"
This directly subsets the continent column to only rows where country equals "Bahamas" and updates the value—super straightforward.
Approach 3: Loop (As Requested)
While loops aren't the most efficient for this task, here's how you'd implement one if you need to:
# Loop through each row to check and update for (i in 1:nrow(df)) { if (df$country[i] == "Bahamas") { df$continent[i] <- "South America" } }
This iterates over every row, checks if the country is "Bahamas", and updates the continent value when a match is found.
Verify the Change
To confirm the update worked, you can filter to view just the "Bahamas" row:
df[df$country == "Bahamas", ]
内容的提问来源于stack exchange,提问作者ChinookJargon

