如何在data.table中按指定Model值选择对应列及右侧3列?
Hey there! Let's tackle this step by step. First, it looks like your data.table is a wide-format table where each model's results (Model value, Variable, Coefficient, standardized coefficient) are grouped into sets of 4 columns. Since data.table doesn't allow duplicate column names, those repeated columns probably got automatic suffixes like .1, .2 under the hood.
Here's how you can select the exact columns you need:
- First, we'll locate which "Model" column contains the value stored in
new_num(which is "0.3" in your case). - Then, we'll grab that column plus the next 3 columns right beside it—these correspond to the Variable, Coefficient, and standardized coefficient for that target model.
Here's the ready-to-use code:
# Assuming your data.table is named `dt` new_num <- "0.3" # Use 0.3 instead if your Model values are stored as numeric # Find positions of all columns starting with "Model" model_col_positions <- which(startsWith(names(dt), "Model")) # Identify which Model column holds the target value target_column_idx <- model_col_positions[sapply(model_col_positions, function(pos) any(dt[[pos]] == new_num))] # Extract the target column and the 3 columns immediately to its right selected_dt <- dt[, target_column_idx:(target_column_idx + 3), with = FALSE] # Optional: Clean up column names to remove any auto-generated suffixes setnames(selected_dt, c("Model", "Variable", "Coefficient", "standardized coefficient"))
Running this will give you exactly the output you're expecting: a tidy data.table with the Model 0.3 rows and its matching Variable, Coefficient, and standardized coefficient columns.
内容的提问来源于stack exchange,提问作者Nick Knauer
相关产品推荐
相关产品推荐

