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

R语言对字符列执行pivot_wider出现大量NA值怎么解决?

问题原因

你当前代码中生成的id列是全局唯一的行号(取值1到252),pivot_wider执行宽转换时会将行标识列的所有唯一值作为输出的独立行,而每个id仅对应col的其中一个取值,因此最终输出保留了全部252行,其余列自动填充NA。

解决代码

你需要将id改为col分组内的同位置序号,让a/b/c/d四组中相同位置的元素共享同一个id:

library(stringi)
library(tidyverse)

stri_rand_strings(252, 5, '[a-z]') %>%
  sort() %>%
  as_tibble() %>%
  mutate(
    id = rep(1:(length(value)/4), times = 4),
    col = rep(letters[1:4], each = length(value) / 4)
  ) %>%
  pivot_wider(names_from = col, values_from = value)
输出验证

运行上述代码后将得到63行×5列的tibble,列分别为id、a、b、c、d,无NA值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 09:36:05