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

如何用tidyverse将数据框所有非NA字符串合并为单列

使用tidyverse实现多列非NA字符串堆叠为单列数据框

你可以通过tidyverse中的pivot_longer结合filter函数快速实现需求,完整代码如下:

library(tidyverse)

# 定义输入数据框
df.input <- data.frame(col1 = c("green potatoes","read avocados","white pepper","wise master"),
                      col2 = c("white seagull","black tank","creative pigeon","crazy socks"),
                      col3 = c("constant turmoil","ready fan",NA,"interesting collapse"),
                      col4 = c("awesome lettuce","jiggedy cabbage",NA,NA),
                      col5 = c("green potatoes","read avocados",NA,NA),
                      col6 = c("green potatoes",NA,NA,NA),
                      col7 = c(NA,NA,NA,NA)
                      )

# 转换并过滤
df.output <- df.input %>%
  pivot_longer(
    cols = everything(),  # 选中所有列进行长格式转换
    names_to = NULL,      # 丢弃原列名,不生成额外列
    values_to = "colOnlyOne"  # 指定新列的名称
  ) %>%
  filter(!is.na(colOnlyOne))  # 移除所有NA值

# 查看最终结果
print(df.output)

步骤说明:

  • pivot_longer:将宽格式数据转换为长格式,cols = everything()确保所有列都被处理;names_to = NULL避免保留原列名的冗余列;values_to定义了最终单列的名称。
  • filter(!is.na(colOnlyOne)):筛选出列中所有非NA的有效字符串,得到你需要的单列数据框。

运行后得到的df.output就是仅包含非NA字符串的单列数据框,和你期望的输出结构完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 02:18:14