R语言按ID合并多列为一列:尝试方法无效求助
Hey there! Let's work through this problem since your previous attempts with gather and grouping didn't give you the results you wanted. Since you didn't share your raw data or exact desired output, I'll cover the two most common scenarios for this task.
Scenario 1: Aggregate Numeric Columns by ID (Sum, Mean, etc.)
Your grouping sum failed because you were trying to sum a factor column—R can't do that directly! First, we need to convert factor columns to numeric values properly, then run the aggregation.
Fix the Factor-to-Numeric Conversion
When converting factors, don't use as.numeric() directly (it will return factor levels instead of the actual values). Use this instead:
library(dplyr) # Convert factor column to numeric (replace `B` with your column name) df <- df %>% mutate(B = as.numeric(as.character(B)))
Group by ID and Aggregate
Now you can safely group by your ID column (I'll assume it's named ID—replace it with your actual column name) and calculate sums or other metrics:
# Group by ID and sum the converted numeric column result <- df %>% group_by(ID) %>% summarise(total = sum(B, na.rm = TRUE)) # Add na.rm = TRUE to ignore missing values
Scenario 2: Combine Text/Values from Multiple Columns into a Single String by ID
If you want to concatenate content from multiple columns (e.g., merge text entries for the same ID), use pivot_longer (the modern replacement for gather) to reshape your data first, then group and concatenate.
Step-by-Step Code
library(dplyr) library(tidyr) library(stringr) # For flexible string concatenation # Reshape wide data to long format (keep ID, convert all other columns to key-value pairs) result <- df %>% pivot_longer(cols = -ID, # Exclude the ID column from reshaping values_to = "content") %>% # Name the column holding your values group_by(ID) %>% summarise(combined_content = str_c(content, collapse = ", ")) # Customize the separator (e.g., " | " instead of ", ")
Note on Your Previous gather Attempt
If you still want to use gather (it's deprecated but still works), make sure you specify which columns to reshape. For example, to keep your ID column and reshape others:
long_data <- gather(Learning_platform, key = "column_name", value = "value", -ID)
Then you can group this long data by ID and combine values as needed.
Quick Troubleshooting Tips
- Use
str(df)to check the data types of your columns—make sure numeric columns are actually numeric, not factors. - Double-check your ID column name for typos in the
group_by()call. - If dealing with missing values, add
na.rm = TRUEto aggregation functions (likesum()) orstr_c(content, collapse = ", ", na.rm = TRUE)for string concatenation.
内容的提问来源于stack exchange,提问作者marine8115

