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

使用cast函数重塑DataFrame报错:undefined columns selected 求助

问题解决:cast函数重塑数据报错修复

错误原因

报错核心是列名大小写不匹配:你的数据集里数值列名称是Salary(首字母大写),但代码中cast函数的value参数指定的是小写的"salary"。R对大小写严格区分,因此找不到对应列,触发"undefined columns selected"错误。

修正后的代码(使用reshape包)

将value参数的值改为大写的"Salary",同时确保数据集名称为populations(与代码中引用一致):

library(reshape)
transdara <- as.data.frame(cast(populations, ID ~ Rank, 
                                fun.aggregate = sum, value = "Salary"))
transdara

运行后会生成以ID为行、Rank各取值为列、对应Salary求和结果的宽表。

更推荐的方案:使用reshape2包的dcast

reshape包相对老旧,reshape2包的dcast函数语法更清晰稳定,用法如下:

library(reshape2)
transdara <- dcast(populations, ID ~ Rank, 
                   fun.aggregate = sum, value.var = "Salary")
transdara

该写法逻辑与reshape的cast一致,但参数名value.var更明确,可读性和维护性更强。

示例输出

基于你提供的数据集,运行修正代码后输出如下:

ID AssocProf AsstProf    Prof
1   11    119800        0       0
2   44         0        0  231545
3   78         0        0  193000
4   92         0    97032       0
5  152         0    95079       0
6  199    113600        0       0
7  200         0    92700       0
8  202         0        0  189409
9  204         0    92700       0
10 218    118700        0       0
11 253         0        0  204000
12 275         0        0  194800
13 326    126431        0       0
14 334         0        0  192253
15 368         0        0  205500

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 01:55:17