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

如何用tidyverse的dplyr::mutate()生成长度由count列决定的数据框列表列

在dplyr中为数据框添加包含重复'1'的列表列

问题描述

我有一个包含name列和count列的数据框,示例如下:

df = read.table(header=TRUE, text= 
'name count
a 10
b 1
c 7
d 3')

输出的df为:

name count    
1    a    10        
2    b     1      
3    c     7  
4    d     3  

希望添加一个名为tally的列,该列是由对应count数量的'1'组成的列表,输出效果如下:

name count    tally
1    a    10        c('1', '1', '1', '1', '1', '1', '1', '1', '1', '1')
2    b     1        c('1')
3    c     7        c('1', '1', '1', '1', '1', '1', '1')
4    d     3        c('1', '1', '1')

尝试用for循环实现但无法优雅地合并结果,希望使用{tidyverse}中的dplyr::mutate()来解决。

解决方案

可以结合dplyr::mutate()和purrr::map()来实现,map()会对count列的每个值生成对应长度的'1'字符向量,最终存储为列表列:

library(tidyverse)

df <- df %>%
  mutate(tally = map(count, ~ rep("1", .x)))

结果说明

运行上述代码后,tally列是列表类型,每个元素都是对应长度的'1'向量。打印数据框时会显示为:

print(df)
name count                                                                 tally
1    a    10 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
2    b     1                                                                      1
3    c     7                          1, 1, 1, 1, 1, 1, 1
4    d     3                                      1, 1, 1

如果需要将tally列显示为c('1', ...)格式的字符串(而非列表向量),可以用stringr和glue来格式化:

library(tidyverse)
library(glue)

df <- df %>%
  mutate(tally = map_chr(count, ~ glue("c('{str_c(rep('1', .x), collapse=\"', '\")}')")))

此时tally列是字符串类型,打印后会完全符合你给出的示例格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 03:32:37