gpt4 book ai didi

r - 查找/替换或映射,使用 R 中的查找表

转载 作者:行者123 更新时间:2023-12-03 23:21:48 28 4
gpt4 key购买 nike

完全 R 新手,在这里。请温柔点。

我在数据框中有一列数值代表种族(英国人口普查数据)。

# create example data
id = c(1, 2, 3, 4, 5, 6, 7, 8, 9)
ethnicode = c(0, 1, 2, 3, 4, 5, 6, 7, 8)
df = data.frame(id, ethnicode)

我可以进行映射(或查找/替换)以创建包含人类可读值的列(或编辑现有列):
# map values one-to-one from numeric to string
df$ethnicity <- mapvalues(df$ethnicode,
from = c(8, 7, 6, 5, 4, 3, 2, 1, 0),
to = c("Other", "Black", "Asian", "Mixed",
"WhiteOther", "WhiteIrish", "WhiteUK",
"WhiteTotal", "All"))

在我尝试过的所有事情中,这似乎是最快的(900 万行大约 20 秒,而不是一些方法超过一分钟)。

我似乎找不到(或从我读过的内容中无法理解)的是如何引用查找表。
# create lookup table
ethnicode = c(8, 7, 6, 5, 4, 3, 2, 1, 0)
ethnicity = c(("Other", "Black", "Asian", "Mixed", "WhiteOther",
"WhiteIrish", "WhiteUK", "WhiteTotal", "All")
lookup = data.frame(ethnicode, ethnicity)

关键是,如果我想更改人类可读的字符串,或对该过程执行任何其他操作,我宁愿对查找表执行一次,而不必在多个脚本中的多个位置执行此操作...如果我能更有效地完成它(900 万行不到 20 秒),那也很好。

我还想轻松确保“8”仍然等于“其他”(或任何等效项),“0”仍然等于“全部”等,这在视觉上更困难,使用上述方法的列表更长。

提前致谢。

最佳答案

您可以为此使用命名向量。但是,您需要将ethnicode 转换为字符。

df = data.frame(
id = c(1, 2, 3, 4, 5, 6, 7, 8, 9),
ethnicode = as.character(c(0, 1, 2, 3, 4, 5, 6, 7, 8)),
stringsAsFactors=FALSE
)

# create lookup table
ethnicode = c(8, 7, 6, 5, 4, 3, 2, 1, 0)
ethnicity = c("Other", "Black", "Asian", "Mixed", "WhiteOther",
"WhiteIrish", "WhiteUK", "WhiteTotal", "All")
lookup = setNames(ethnicity, as.character(ethnicode))

然后你可以做
df <- transform(df, ethnicity=lookup[ethnicode], stringsAsFactors=FALSE)

你就完成了。

要处理 900 万行,我建议您使用 sqlite 或 monetdb 之类的数据库。对于 sqlite,以下代码可能会有所帮助:
library(RSQLite)

dbname <- "big_data_mapping.db" # db to create
csvname <- "data/big_data_mapping.csv" # large dataset

ethn_codes = data.frame(
ethnicode= c(8, 7, 6, 5, 4, 3, 2, 1, 0),
ethnicity= c("Other", "Black", "Asian", "Mixed", "WhiteOther", "WhiteIrish", "WhiteUK", "WhiteTotal", "All")
)

# build db
con <- dbConnect(SQLite(), dbname)
dbWriteTable(con, name="main", value=csvname, overwrite=TRUE)
dbWriteTable(con, name="ethn_codes", ethn_codes, overwrite=TRUE)

# join the tables
dat <- dbGetQuery(con, "SELECT main.id, ethn_codes.ethnicity FROM main JOIN ethn_codes ON main.ethnicode=ethn_codes.ethnicode")

# finish
dbDisconnect(con)
#file.remove(dbname)
monetdb据说更适合您通常使用 R 完成的任务,因此绝对值得一看。

关于r - 查找/替换或映射,使用 R 中的查找表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39001057/

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