gpt4 book ai didi

r - 如何根据 R 中的字典将带有代码的 data.frame 映射到字符串

转载 作者:行者123 更新时间:2023-12-02 17:59:24 24 4
gpt4 key购买 nike

mydata <- data.frame(id = 1:5,
item1 = c("", "", "1222", "1222", ""),
item2 = c("13", "", "", "", "382"))
> mydata
id item1 item2
1 1 13
2 2
3 3 1222
4 4 987
5 5 382

我有一个数据集,其中包含不同的代码。我想将这些代码映射到基于字典

的字符串
dictionary <- data.frame(code = c(1, 13, 382, 987, 1222),
entry = c("ballet", "soccer", "basketball", "painting", "pottery"))
> dictionary
code entry
1 1 ballet
2 13 soccer
3 382 basketball
4 987 painting
5 1222 pottery

所需的输出是带有字符串的 data.frame:

  id   item1      item2
1 1 soccer
2 2
3 3 pottery
4 4 pottery
5 5 basketball

最佳答案

mydata <- data.frame(id = 1:5,
item1 = c("", "", "1222", "1222", ""),
item2 = c("13", "", "", "", "382"))

dictionary <- data.frame(code = c(1, 13, 382, 987, 1222),
entry = c("ballet", "soccer", "basketball", "painting", "pottery"))

mydata$item1 <- ifelse(mydata$item1 %in% dictionary$code,
dictionary$entry[match( mydata$item1,dictionary$code)], "")

mydata$item2 <- ifelse(mydata$item2 %in% dictionary$code,
dictionary$entry[match( mydata$item2,dictionary$code)], "")

mydata
#> id item1 item2
#> 1 1 soccer
#> 2 2
#> 3 3 pottery
#> 4 4 pottery
#> 5 5 basketball

创建于 2022 年 12 月 15 日,使用 reprex v2.0.2

注意:

当然,执行此操作的规范方法是使用因子(和 NA 而不是空字符串):

factor(mydata$item1, dictionary$code, dictionary$entry)
# <NA> <NA> pottery pottery <NA>

关于r - 如何根据 R 中的字典将带有代码的 data.frame 映射到字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74806744/

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