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

R语言:如何用不同数据框的不等长列创建new_df?

合并不同长度列生成新数据框

问题描述

需从Kube_liten和Kube_Stor两个数据框中提取Unit_cm列,合并为名为new_df的新数据框,但两列长度不一致,需用NA填充空缺单元格。已加载的R包包括:tidyverse、ggplot2、here、readxl、gt。

解决方法

利用tidyverse工具可轻松实现补NA并合并,具体步骤如下:

  1. 计算两列的最大长度,确定需要填充的NA数量:
max_len <- max(length(Kube_liten$Unit_cm), length(Kube_Stor$Unit_cm))
  1. 将每一列补全至最大长度,空缺位置填充NA:
col_liten <- c(Kube_liten$Unit_cm, rep(NA, max_len - length(Kube_liten$Unit_cm)))
col_stor <- c(Kube_Stor$Unit_cm, rep(NA, max_len - length(Kube_Stor$Unit_cm)))
  1. 创建新数据框new_df:
new_df <- tibble(
  Kube_liten_Unit_cm = col_liten,
  Kube_Stor_Unit_cm = col_stor
)

更简洁的tidyverse写法

结合purrr可一步完成操作:

library(purrr)

new_df <- list(
  Kube_liten_Unit_cm = Kube_liten$Unit_cm,
  Kube_Stor_Unit_cm = Kube_Stor$Unit_cm
) %>%
  map_dfc(~ .x %>% as_tibble() %>% slice(1:max(lengths(.))))

生成的new_df中,较短列的空缺行将自动填充NA,确保两列长度一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 16:16:06