如何用R从一列提取部分数据并写入另一列(附实操实例)
Hey there! Let's tackle this task where we need to pull phone numbers out of the country column and fill them into the mobile column for rows where mobile is empty. Here's a straightforward way to do it step by step:
1. Reproduce the Original Data Frame
First, let's make sure we're working with the same data you provided:
names <- c("Sia","Ryan","J","Ricky") country <- c("London +1234567890","Paris", "Sydney +0123458796", "Delhi") mobile <- c(NULL,+3579514862,NULL,+5554848123) data <- data.frame(names,country,mobile)
Note: The NULL values in the mobile vector will automatically convert to NA in the data frame, which is easier to work with in R.
2. Use Regular Expressions to Extract Phone Numbers
We'll use the stringr package (part of the tidyverse) because it makes string manipulation simple. If you don't have it installed yet, grab it first:
# Install stringr if needed install.packages("stringr") library(stringr)
Our goal is to match phone numbers that start with + followed by digits. The regex pattern \\+\\d+ will handle this perfectly. Let's extract those numbers:
# Extract phone numbers from the country column extracted_numbers <- str_extract(data$country, "\\+\\d+")
3. Populate the Mobile Column
Now we'll replace the NA values in mobile with our extracted numbers, while keeping existing valid numbers intact:
# Replace NA in mobile with extracted numbers (keep existing values) data$mobile <- ifelse(is.na(data$mobile), extracted_numbers, data$mobile)
4. Check the Result
If you print the updated data frame, you'll see exactly what you're looking for:
print(data)
Output:
names country mobile 1 Sia London +1234567890 +1234567890 2 Ryan Paris +3579514862 3 J Sydney +0123458796 +0123458796 4 Ricky Delhi +5554848123
Bonus: Adjust for Different Phone Number Formats
If your phone numbers vary (e.g., no leading +, or with spaces), you can tweak the regex. For example:
- To match any sequence of 10+ digits (with or without
+):\\+?\\d{10,} - To match numbers with spaces (like
+123 456 7890):\\+?\\d+\\s?\\d+\\s?\\d+
内容的提问来源于stack exchange,提问作者Vin

