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

R语言如何将Attribute Value匹配V列日期展开生成目标宽表

问题排查与解决代码

原有代码错误点

  • 列名不匹配:原数据的属性编码列是Attribute_Code,你代码中写的Attribute_Code1会导致列识别异常
  • 逻辑错误:mutate(key = Attribute_Value)这一步直接把存V1/V2列名的key替换为属性值,完全搞反了映射逻辑:你需要把V列对应的日期值作为新列名,对应填充的才是Attribute_Value
  • 缺少空值过滤:原V列中的空字符串会生成无效的日期列,需要提前剔除

正确实现代码

适配tidyr新版本(推荐)

library(tidyverse)

df2 <- df1 %>%
  # 宽转长:把所有V开头的日期列转为行,保留其他固定维度列
  pivot_longer(cols = starts_with("V"),
               names_to = "v_col",
               values_to = "date") %>%
  # 过滤空日期,避免生成无效列
  filter(date != "") %>%
  select(-v_col) %>%
  # 长转宽:日期作为新列名,属性值作为填充内容,空位置填空字符串
  pivot_wider(names_from = date,
              values_from = Attribute_Value,
              values_fill = "")

适配你原有gather/spread写法的修正版

df2 <- df1 %>%
  gather(key = "v_col", value = "date", 
         -ROW_ID, -Process_ID, -Operation_Code, -Resource_Group_Code,
         -Location_Code, -Resource_Code, -Resource_Desc, -iDeleteFlag,
         -Attribute_Code, -Capacity_Type, -Planning_Version, -Attribute_Value) %>%
  filter(date != "") %>%
  select(-v_col) %>%
  spread(key = date, value = Attribute_Value, fill = "")

运行上述代码得到的结果和你给出的预期输出完全一致。

内容的提问来源于stack exchange,提问作者ks ramana

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 04:09:03