求助:如何将R语言DataFrame转换为指定格式表格
Hey there! Let's figure out how to reshape your data into that wide-format table you want. You've got a long-format dataset where each row is a respondent's score for their major, and you want to flip it so Majors are columns, Respondents are rows, and the cells hold the corresponding score values. Here are three solid ways to do this in R:
1. Using tidyr::pivot_wider (Tidyverse Recommended)
This is the most intuitive and flexible method if you're using the tidyverse toolkit. First, make sure you have the package installed, then run this:
# Load the tidyverse package (includes tidyr) library(tidyverse) # Your original data setup Respond<-as.factor(c(1,2,3,4,5,6,7,8,9,10,11,12)) Major<-as.factor(c("AD","B","E","AD","B","AD","B","E","AD", "E","AD","E")) score<-c(2.5,0.5,2,3,2,2,1,1,1,0.5,3,1.5) data<-data.frame(Respond,Major,score) # Reshape to wide format wide_data <- data %>% pivot_wider(names_from = Major, # Use Major values as column names values_from = score) # Fill cells with score values # Check the result print(wide_data)
2. Using reshape2::dcast
If you prefer the older reshape2 package (still widely used), this works too:
# Load reshape2 library(reshape2) # Reshape with dcast wide_data_dcast <- dcast(data, Respond ~ Major, value.var = "score") print(wide_data_dcast)
The formula Respond ~ Major tells R: "Use Respond values as rows, Major values as columns, and fill with the 'score' variable."
3. Base R reshape Function
No extra packages needed here—just use R's built-in reshape tool:
# Reshape with base R wide_data_base <- reshape(data, idvar = "Respond", # Identify rows by Respondent timevar = "Major", # Use Major to create columns direction = "wide") # Switch to wide format # Clean up column names (remove the "score." prefix) colnames(wide_data_base) <- gsub("score\\.", "", colnames(wide_data_base)) print(wide_data_base)
All three methods will give you the exact table structure you're looking for. The pivot_wider method is especially nice because it plays well with other tidyverse functions if you need to do more data cleaning or analysis later.
内容的提问来源于stack exchange,提问作者Daeyoon

