将列的值替换为另一列,我正在处理数据集的预处理过程。这里是我的数据集的透视图
BSTN ASTN
150 216
300 222
4310 35
60 4310
150 23
4310 60
. .
. .
. .数字BSTN ASTN表示站的代码号我有另一个BSTN数据集,ASTN编号显示站号。下面是它看起来的样子
Station code Station
150 A
300 A
4310 B
23 C
60 C
. .
. .
. .问题是有些电台有两个或两个以上的代码。例如,A站的车站代码是150,300
I希望将具有多个站号的BSTN和ASTN中的站号统一为一个统一的站号。我还想将BSTN,ASTN中的代码编号统一为一个频率更高的数字。
BSTN ASTN
150 216
150 222
4310 35
60 4310
150 60
4310 60
. .
. .
. .我想要的最后输出如下所示。
我很感谢你的帮助
发布于 2020-06-11 03:58:22
让我们进入你的数据
library(readr)
stations <- read_table(
"BSTN ASTN
150 216
300 222
4310 35
60 4310
150 23
4310 60")
stCodex <- read_table(
"Station_code Station
150 A
300 A
4310 B
23 C
60 C "
)让我们把两个列都放在一个tibble中,这样我们就可以找出每个站点最流行的Station_code是什么
st2 <- tibble(replaceBy = c(stations$BSTN, stations$ASTN)) %>%
left_join(stCodex, by = c("replaceBy" = "Station_code")) %>%
filter(!is.na(Station)) %>%
group_by(Station, replaceBy) %>%
summarise(Count = n()) %>%
# We have a count of each Station's Station_codes. Find the most frequent
mutate(BestCount = max(Count)) %>%
filter(Count == BestCount) %>%
summarise_all(~ first(.)) %>%
arrange(Station) %>%
select(Station, replaceBy)看上去像是:
# A tibble: 3 x 2
Station replaceBy
<chr> <dbl>
1 A 150
2 B 4310
3 C 60构建一个替换表-用更高的替换表替换低频率的Station_codes。
rplc <- stCodex %>%
left_join(st2, by = "Station") %>%
filter(Station_code != replaceBy) %>%
select(- Station)给予
# A tibble: 2 x 2
Station_code replaceBy
<dbl> <dbl>
1 300 150
2 23 60 先在BSTN中,然后在ASTN中进行替换。
stations %>%
left_join(rplc, by = c(BSTN ="Station_code")) %>%
mutate(BSTN = ifelse(is.na(replaceBy), BSTN, replaceBy)) %>%
select(- replaceBy) %>%
left_join(rplc, by = c(ASTN ="Station_code")) %>%
mutate(ASTN = ifelse(is.na(replaceBy), ASTN, replaceBy)) %>%
select(- replaceBy)答案是
# A tibble: 6 x 2
BSTN ASTN
<dbl> <dbl>
1 150 216
2 150 222
3 4310 35
4 60 4310
5 150 60
6 4310 60https://stackoverflow.com/questions/62316374
复制相似问题