You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

使用tidyr::pivot_wider时遇「Values are not uniquely identified」警告的解决求助

使用tidyr::pivot_wider时遇「Values are not uniquely identified」警告的解决求助

大家好,我现在在处理一个数据格式转换的问题,遇到了点麻烦,想请教一下各位。

我有一个名为dfmelt的数据框,想要把它从长格式转成宽格式。它包含五列:study_idredcap_event_name是用来分组的ID列,variablevalue是键值对,还有一个数值列num——这个列是按study_idredcap_event_name分组生成的序列(1、2…n),我希望把这个num作为后缀直接拼在宽格式的列名后面,比如micro_sample_dt1这种形式,不需要分隔符。

以下是我的数据片段:

study_idredcap_event_namevariablevaluenum
CHLA_0014csf_shunt_infectio_arm_1micro_sample_dt7/22/211
CHLA_0014csf_shunt_infectio_arm_1micro_sample_dt7/22/212
CHLA_0014csf_shunt_infectio_arm_1micro_sample_dt7/22/213
CHLA_0014csf_shunt_infectio_arm_1micro_sample_time18:191
CHLA_0014csf_shunt_infectio_arm_1micro_sample_time18:382
CHLA_0014csf_shunt_infectio_arm_1micro_sample_time18:383
CHLA_0067initial_shunt_plac_arm_1micro_culture_source11
CHLA_0067initial_shunt_plac_arm_1micro_culture_source12
CHLA_0067initial_shunt_plac_arm_1micro_culture_source13

我尝试用tidyr::pivot_wider来实现,代码如下:

pivot_wider(dfmelt, id_cols = c(1:2), names_from = c(variable), values_from = c(value), names_glue = "{variable}{num}")

但运行后收到了这样的警告:

Warning message:
Values are not uniquely identified; output will contain list-cols.

我想要的目标格式是这样的(缺失值用NA填充就可以):

study_idredcap_event_namemicro_sample_dt1micro_sample_time1micro_culture_source1micro_sample_dt2micro_sample_time2micro_culture_source2micro_sample_dt3micro_sample_time3micro_culture_source3
CHLA_0014csf_shunt_infectio_arm_17/22/2118:19NA7/22/2118:38NA7/22/2118:38NA
CHLA_0067initial_shunt_plac_arm_11NA11NA11NA1

想请教大家,我该怎么修改代码才能得到预期的宽格式,同时消除这个警告呢?

备注:内容来源于stack exchange,提问作者Nishad Gulvady

火山引擎 最新活动