如何在R语言中将指定Dataframe转换为目标宽格式表格?
Hey there! Let's work through reshaping your data into the desired format in R first, I need to clarify your original DataFrame structure since the formatting was a bit messy—it looks like you have two columns: one (let's call it a) with group identifiers, and another (b) holding the values q, w, e. Your goal is to count how many times each value appears per group, then pivot it into a wide table with q, w, e as columns.
Here are two straightforward, easy-to-follow ways to make this happen:
1. Using the Tidyverse (dplyr + tidyr)
This is perfect if you prefer a readable, pipe-based workflow:
First, load the necessary packages:
library(tidyverse)
Assuming your cleaned-up original data looks like this (matching the structure implied by your target output):
df <- data.frame( a = c(1, 1, 1, 2, 2, 2, 3, 3, 3, 3), b = c("q", "w", "e", "q", "w", "e", "q", "w", "e", "e") )
Now, count occurrences per group and reshape to wide format:
result <- df %>% count(a, b) %>% # Count how many times each `b` value shows up in each `a` group pivot_wider( names_from = b, # Use `b` values as column headers values_from = n, # Use the counts as cell values values_fill = 0 # Fill any missing counts with 0 (not strictly needed here, but safe) ) %>% select(-a) # Remove the group column since your target doesn't include it
The output will be exactly what you're looking for:
# A tibble: 3 × 3 q w e <int> <int> <int> 1 1 1 1 2 1 1 1 3 1 1 2
2. Using Base R (No External Packages)
If you don't want to load extra libraries, use the built-in table() function:
# Create a cross-tabulation of groups vs values tab <- table(df$a, df$b) # Convert the table to a regular data frame result <- as.data.frame.matrix(tab) # Remove row names to match your target format rownames(result) <- NULL
This gives the exact same result as the tidyverse method:
q w e 1 1 1 1 2 1 1 1 3 1 1 2
Just double-check that your original data is structured as two columns (group and value pairs). If your actual data has slightly different groupings, tweak the code accordingly—but this should fit your described target perfectly.
内容的提问来源于stack exchange,提问作者소재룡

