You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按重复日期转置DataFrame,将type转为列、effort为对应值?

将长格式DataFrame转换为宽格式

给定如下长格式的R DataFrame:

structure(list(Date = structure(c(18876, 18878, 18876, 18878, 
18876, 18878), class = "Date"), effort = c(2371.5, 1950.66666666667, 
6107.25, 3318.66666666667, 4154.83867521367, 2073.10096153846
), type = c("aerial", "aerial", "TLAcmeth", "TLAcmeth", "TLAmeandaily", 
"TLAmeandaily")), row.names = c(NA, -6L), class = c("tbl_df", 
"tbl", "data.frame"))

需要将其转换为以Date为第一列,每个type对应单独列的宽格式,目标格式如下:

DateaerialTLAcmethTLAmeandaily
2021-09-062371.56107.254154.839
2021-09-081950.6673318.6672073.101

解决方案

使用tidyr包中的pivot_wider()函数可完成这类数据重塑,同时通过round()调整小数位数匹配目标格式:

# 若未安装tidyr包先执行安装
# install.packages("tidyr")
library(tidyr)

# 转换为宽格式并调整小数位数
wide_df <- df %>%
  pivot_wider(names_from = type, values_from = effort) %>%
  mutate(across(-Date, ~round(., 3)))

# 查看结果
print(wide_df)

执行后得到的结果与目标格式一致:

# A tibble: 2 × 4
  Date       aerial TLAcmeth TLAmeandaily
  <date>      <dbl>    <dbl>        <dbl>
1 2021-09-06  2371.5    6107.25        4154.839
2 2021-09-08  1950.667  3318.667       2073.101

内容的提问来源于stack exchange,提问作者Ryan Gary

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 20:56:31