首页 > 解决方案 > 根据数据的可用性创建重复行

问题描述

我试图用分隔符分割一列,在这种情况下是逗号,然后根据逗号之间的元素数量制作重复的行。我使用了 str_split_fixed() 它将适当地拆分列,但我不知道如何使用它来制作重复的行。

例如,我有这个数据框:

V1  V2 V3 V4
foo a  b  1,2,3  
bar c  d  1,2

并希望将其作为输出发送到此数据框:

V1  V2 V3 V4
foo a  b  1
foo a  b  2
foo a  b  3
bar c  d  1
bar c  d  2

标签: r

解决方案


为此,有separate_rows

library(tidyverse)
df1 %>%
     separate_rows(V4, sep=",", convert = TRUE)
#.  V1 V2 V3 V4
#1 foo  a  b  1
#2 foo  a  b  2
#3 foo  a  b  3
#4 bar  c  d  1
#5 bar  c  d  2

数据

df1 <- structure(list(V1 = c("foo", "bar"), V2 = c("a", "c"), V3 = c("b", 
"d"), V4 = c("1,2,3", "1,2")), class = "data.frame", row.names = c(NA, 
-2L))

推荐阅读