gpt4 book ai didi

R - 从另一个图例中拆分列

转载 作者:行者123 更新时间:2023-12-04 11:54:01 25 4
gpt4 key购买 nike

我有如下所示的 data.frame

ID  age legend                 location     
1 83 country;province;city X;A;J
2 15 country;city X;K
3 2 country;province;city Y;B;I
4 12 country;city X;L
5 2 country;city Y;J
6 2 country;province;city Y;A;M
7 18 country;province;city X;B;J
8 85 country;province;city X;A;I

描述它:第三列(图例)描述了第四列(位置)的值。 legend 列的行中记录的顺序指示 location 列中值的顺序。

因此,我需要获取如下的data.frame

ID age country province city
1 83 X A J
2 15 X <NA> K
3 2 Y B I
4 12 X <NA> L
5 2 Y <NA> J
6 2 Y A M
7 18 X B J
8 85 X A I

为了描述,我需要从图例列中提取信息并将它们设置为新列的名称,然后从位置列中填充适当的信息。我不能只将列拆分为 ;因为每行中的记录数不同。有什么建议吗?

最佳答案

使用 DF 在末尾的注释中可重复显示,使用 separate_rows 然后 spread 将数据从长到宽。如果列的顺序无关紧要,则可以省略 select 行。

library(dplyr)
library(tidyr)

DF %>%
separate_rows(legend, location) %>%
spread(legend, location) %>%
select(ID, age, country, province, city) # optional

给予:

  ID age country province city
1 1 83 X A J
2 2 15 X <NA> K
3 3 2 Y B I
4 4 12 X <NA> L
5 5 2 Y <NA> J
6 6 2 Y A M
7 7 18 X B J
8 8 85 X A I

注意事项

Lines <- "
ID age legend location
1 83 country;province;city X;A;J
2 15 country;city X;K
3 2 country;province;city Y;B;I
4 12 country;city X;L
5 2 country;city Y;J
6 2 country;province;city Y;A;M
7 18 country;province;city X;B;J
8 85 country;province;city X;A;I"
DF <- read.table(text = Lines, header = TRUE, as.is = TRUE)

关于R - 从另一个图例中拆分列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54887218/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com