R Pivot Tables Guide: Reshape Data with dplyr
In R language, you can use functions in the dplyr package to perform data pivoting and reshaping operations. Here is an example code:
# 加载dplyr包
library(dplyr)
# 创建一个示例数据框
df <- data.frame(
ID = c(1, 1, 2, 2),
Category = c("A", "B", "A", "B"),
Value = c(10, 20, 30, 40)
)
# 对数据进行透视表操作
pivot_table <- df %>%
group_by(ID) %>%
summarize(
A = sum(Value[Category == "A"]),
B = sum(Value[Category == "B"])
)
# 打印透视表
print(pivot_table)
# 对数据进行重塑操作
reshaped_df <- df %>%
spread(key = Category, value = Value)
# 打印重塑后的数据框
print(reshaped_df)
In the example above, the data is first transformed using the group_by and summarize functions from the dplyr package for creating a pivot table, and then reshaped using the spread function. These functions make it easy to pivot and reshape data.