R中利用start/end列生成position列时嵌套操作报错,求解决方法
问题
想要在数据框中新增position列,计划以start和end列作为seq函数的输入,通过as.list生成嵌套数据后用unnest展开,但执行时报错。
示例输入数据:
tibble( start=c(1,7), end=c(3,10), total=15, value=c(100,200) )
期望输出结果:
tibble( start=c(1,1,1,7,7,7,7), end=c(3,3,3,10,10,10,10), total=15, value=c(100,100,100,200,200,200,200), position=c(1,2,3,7,8,9,10) )
尝试的代码:
tibble( start=c(1,7), end=c(3,10), total=15, value=c(100,200) ) %>% mutate(position=as.list(seq(start,end))) %>% unnest(position)
错误原因
当前代码里的seq(start, end)是直接对整个start和end列向量计算的,不是逐行生成序列。比如seq(c(1,7), c(3,10))会生成1,2,3,4,5,6,7,8,9,10这个长序列,套as.list也只是把这个长序列转成列表,没法对应到每行的需求,自然会在unnest时出错。
修正方法
有两种简单的解决方式:
方法1:用rowwise()逐行处理
先让数据框按行分组,再逐行生成position的列表:
library(tidyverse) tibble( start=c(1,7), end=c(3,10), total=15, value=c(100,200) ) %>% rowwise() %>% mutate(position = list(seq(start, end))) %>% unnest(position)
方法2:用map2()映射每行的start和end
map2可以同时对两个列的元素逐对应用函数,直接生成每行对应的序列列表:
library(tidyverse) tibble( start=c(1,7), end=c(3,10), total=15, value=c(100,200) ) %>% mutate(position = map2(start, end, seq)) %>% unnest(position)
两种方法都能得到你想要的输出结果。
内容的提问来源于stack exchange,提问作者drmariod
相关产品推荐
相关产品推荐

