在多个连接的行上使用 tidyr::separate_rows
Using tidyr::separate_rows on multiple connected rows
我有一些数据是我使用某些文本识别软件从离线来源中清除的。它看起来像下面的数据,但不那么精灵。
elvish_ring_holders_unclean <- tibble(
name=c("Gandalf", "Galadriel", "Elrond", "Cirdan\n\nGil-Galad"),
city = c("Undying Lands","Lothlorien","Rivendell", "Mithlond\n\nLindon"),
race = c("Maiar", "Elf", "Elf", "Elf\n\nElf"))
这两个数据集的问题是某些行已与空格连接在一起。我更喜欢下面的数据,每个观察都有自己的行
elvish_ring_holders <- tibble(
name=c("Gandalf", "Galadriel", "Elrond", "Cirdan","Gil-Galad"),
city = c("Undying Lands","Lothlorien","Rivendell", "Mithlond", "Lindon"),
race = c("Maiar", "Elf", "Elf", "Elf", "Elf"))
到目前为止,我已经尝试了 tidyr::separate_rows 方法
elvish_ring_holders %>%
separate_rows(name, sep = "\n\n") %>%
separate_rows(city, sep = "\n\n") %>%
separate_rows(race, sep = "\n\n") %>%
distinct()
但是,我最终得到了一个数据集,其中 Gil-Galad 和 Cirdan 都对两个不同的城市进行了两次观察,一个是真实的城市,一个是虚假的城市。
在我的外部数据中,我的种族变量也可以通过这种方式进行复制,并且数据具有更多的观测值。我正在寻找的是一些分隔行的方法,这些方法可以跨多个列分隔一次。
与其将每一列单独分开,不如一次性完成。
elvish_ring_holders_unclean %>%
separate_rows(everything(), sep = "\n\n")
name
city
race
1
Gandalf
Undying Lands
Maiar
2
Galadriel
Lothlorien
Elf
3
Elrond
Rivendell
Elf
4
Cirdan
Mithlond
Elf
5
Gil-Galad
Lindon
Elf
我有一些数据是我使用某些文本识别软件从离线来源中清除的。它看起来像下面的数据,但不那么精灵。
elvish_ring_holders_unclean <- tibble(
name=c("Gandalf", "Galadriel", "Elrond", "Cirdan\n\nGil-Galad"),
city = c("Undying Lands","Lothlorien","Rivendell", "Mithlond\n\nLindon"),
race = c("Maiar", "Elf", "Elf", "Elf\n\nElf"))
这两个数据集的问题是某些行已与空格连接在一起。我更喜欢下面的数据,每个观察都有自己的行
elvish_ring_holders <- tibble(
name=c("Gandalf", "Galadriel", "Elrond", "Cirdan","Gil-Galad"),
city = c("Undying Lands","Lothlorien","Rivendell", "Mithlond", "Lindon"),
race = c("Maiar", "Elf", "Elf", "Elf", "Elf"))
到目前为止,我已经尝试了 tidyr::separate_rows 方法
elvish_ring_holders %>%
separate_rows(name, sep = "\n\n") %>%
separate_rows(city, sep = "\n\n") %>%
separate_rows(race, sep = "\n\n") %>%
distinct()
但是,我最终得到了一个数据集,其中 Gil-Galad 和 Cirdan 都对两个不同的城市进行了两次观察,一个是真实的城市,一个是虚假的城市。
在我的外部数据中,我的种族变量也可以通过这种方式进行复制,并且数据具有更多的观测值。我正在寻找的是一些分隔行的方法,这些方法可以跨多个列分隔一次。
与其将每一列单独分开,不如一次性完成。
elvish_ring_holders_unclean %>%
separate_rows(everything(), sep = "\n\n")
name | city | race | |
---|---|---|---|
1 | Gandalf | Undying Lands | Maiar |
2 | Galadriel | Lothlorien | Elf |
3 | Elrond | Rivendell | Elf |
4 | Cirdan | Mithlond | Elf |
5 | Gil-Galad | Lindon | Elf |