作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有如下所示的 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/
我是一名优秀的程序员,十分优秀!