R语言如何将多个向量合并为数据框并新增列记录原向量名称
R合并向量并保留原向量名的实现方案
你之前的代码不能达到预期是因为直接拼接向量时,原向量的名称信息已经丢失,enframe只能生成序列索引。以下是两种可直接运行的实现方案:
方法1:tidyverse方案(推荐)
利用lst()自动生成命名列表,再通过映射转换为目标结构:
library(tidyverse) # 构造命名列表 + 转换结构 lst(fruits, vehicles, weather) %>% imap_dfr(~ tibble(name = .y, value = .x))
如果更习惯用enframe的写法,也可以选择嵌套结构展开的方式:
lst(fruits, vehicles, weather) %>% enframe(name = "name", value = "value") %>% unnest_longer(value)
两种写法输出的结果完全匹配你给出的示例格式。
方法2:基础R方案
不需要加载第三方包,用内置的stack()函数即可实现:
# 构造命名列表传入stack res <- stack(list(fruits = fruits, vehicles = vehicles, weather = weather)) # 调整列名顺序和命名 res <- res[, c(2,1)] colnames(res) <- c("name", "value") # 如需转为tibble可执行:as_tibble(res)
内容的提问来源于stack exchange,提问作者C.Robin
相关产品推荐
相关产品推荐

