gpt4 book ai didi

r - 使用数据字典应用值替换

转载 作者:行者123 更新时间:2023-12-01 23:12:27 24 4
gpt4 key购买 nike

df1=c("blue,green,green", "blue", "green")
dictionary=data.frame(label=c("blue","green"),value=c(1,2))
want=c("1,2,2","1","2")

我希望使用数据字典替换一些数据。数据 (df1) 在一个单元格中可能有多个条目,以逗号分隔。我查看了 str_replace_all,我可以通过str_replace_all(colors,c("blue"="1","green"="2")) 实现,但我无法创建 c("blue"="1","green"="2") 使用字典数据框。我有一百多个项目要编码,所以硬编码不是一种选择。将不胜感激任何关于如何使这项工作或其他方式的指导!

最佳答案

从字典创建命名向量并使用 str_replace_all

library(dplyr)
library(stringr)
library(tibble)
dictionary %>%
mutate(value = as.character(value)) %>%
deframe %>%
str_replace_all(df1, .)
#[1] "1,2,2" "1" "2"

关于r - 使用数据字典应用值替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69578417/

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