在R语言中实现月份与星期缩写到整数的转换方法咨询
Hey there! Let's break down why your match() with month.abb was returning all NAs, and walk through solid solutions for both your month and weekday conversion tasks.
Why the NA issue with months?
The built-in month.abb vector uses title-case abbreviations (like "Jan", "Feb"), but your data has all-lowercase values ("jan", "feb"). R's string matching is case-sensitive, so those mismatched cases caused match() to fail entirely. No worries—fixing this is straightforward.
Solution 1: Fix case matching for months
You can either standardize the case of your data to match month.abb, or vice versa. Here are two easy approaches:
Option A: Use case-insensitive matching with toupper()
Convert both your month column and month.abb to uppercase (or lowercase) before matching:
# Assume your data frame is named df, with a month column called month_col df$month_num <- match(toupper(df$month_col), toupper(month.abb))
Option B: Use factor() with lowercase levels
Define the factor levels to match your lowercase data directly, then convert to integer:
df$month_num <- as.integer(factor(df$month_col, levels = tolower(month.abb)))
This works because tolower(month.abb) creates a vector of lowercase month abbreviations in order ("jan", "feb", ..., "dec"), so converting the factor to integer gives you 1-12 automatically.
Converting weekday abbreviations to integers
R doesn't have a built-in lowercase weekday abbreviation vector like month.abb, but we can create our own. First, confirm your weekday order: I'll assume you want mon = 1, sun = 7 (adjust if you need Sunday as 1 instead).
Option A: match() with a custom abbreviation vector
# Define your lowercase weekday abbreviations in the order you want weekday_abb <- c("mon", "tue", "wed", "thu", "fri", "sat", "sun") df$weekday_num <- match(df$weekday_col, weekday_abb)
Option B: factor() approach (same logic as months)
df$weekday_num <- as.integer(factor(df$weekday_col, levels = weekday_abb))
Full Example
Let's put it all together with a test data frame to see how it works:
# Create sample data df <- data.frame( month = c("jan", "feb", "mar", "dec", "oct"), weekday = c("mon", "wed", "fri", "sun", "tue") ) # Convert months df$month_num <- match(toupper(df$month), toupper(month.abb)) # Convert weekdays weekday_abb <- c("mon", "tue", "wed", "thu", "fri", "sat", "sun") df$weekday_num <- match(df$weekday, weekday_abb) # View the result print(df)
Running this will output:
month weekday month_num weekday_num 1 jan mon 1 1 2 feb wed 2 3 3 mar fri 3 5 4 dec sun 12 7 5 oct tue 10 2
That should solve both your conversion problems! If you run into edge cases (like non-standard abbreviations), we can tweak the solutions further.
内容的提问来源于stack exchange,提问作者Pearson

