实现获取R数据框中ID列最大后缀编号的自定义函数需求
R: Custom Function
which.max.ID to Get the Highest Suffix from ID_* Column Names Need a function that grabs the largest numeric suffix from your ID_-prefixed column names? Here's a clean solution that fits your exact needs:
Step 1: Define the Custom Function
which.max.ID <- function(df) { # Extract numeric parts from ID_* column names id_suffixes <- as.integer(sub("ID_", "", colnames(df))) # Return the maximum suffix value max(id_suffixes) }
Step 2: Test with Your Sample Data
First, let's set up your example data frames:
df1 <- data.frame(ID_0=c("25","25"), ID_1=c("1","2"), ID_2=c("a","b") ) df2 <- data.frame(ID_0=c("25","25"), ID_1=c("1","2"), ID_2=c("a","b"), ID_3=c("c","d"), ID_4=c("3","4") ) df3 <- data.frame(ID_0=c("25","25") )
Now run the function on each data frame—you'll get exactly the outputs you're looking for:
which.max.ID(df1) # Returns [1] 2 which.max.ID(df2) # Returns [1] 4 which.max.ID(df3) # Returns [1] 0
How It Works
colnames(df)pulls all column names from the input data frame.sub("ID_", "", colnames(df))strips theID_prefix from each name, leaving just the numeric suffix.- We convert these suffixes to integers with
as.integer()somax()can easily find the largest value.
Optional Edge Case Handling
If your data might include columns that don't follow the ID_* pattern, add a filter to only target valid ID_ columns:
which.max.ID <- function(df) { # Keep only columns starting with "ID_" valid_id_cols <- grepl("^ID_", colnames(df)) # Return 0 if no valid ID columns exist (adjust behavior as needed) if (!any(valid_id_cols)) return(0) # Extract and compute the maximum suffix id_suffixes <- as.integer(sub("ID_", "", colnames(df)[valid_id_cols])) max(id_suffixes) }
内容的提问来源于stack exchange,提问作者Neal Barsch
相关产品推荐
相关产品推荐

