gpt4 book ai didi

重命名数据框中的观察

转载 作者:行者123 更新时间:2023-12-04 10:56:38 25 4
gpt4 key购买 nike

我在 R 中有一个数据框,其中一列称为状态。在此列中,所有美国州均缩写,例如NY、ME 等。现在我需要用它们的全名重命名这些值,例如纽约、缅因州等。我尝试了多个函数,例如 rename() 或 revalue(),但不知何故,它们要么给我一个错误通知,要么创建一个新值,这不是我想要的。随附您可以找到我的多次失败之一。我非常感谢各种帮助,因为我已经坚持了几天。也祝大家元旦快乐!

str(rename(zipcode_new,
"AL"="alaska","AK"="alaska","AR"="arizona","AZ"="arizona","CA"="california","CO"="colorado","CT"="conneticut","DE"="delaware","FL"="florida","GA"="georgia","HI"="hawaii","IA"="iowa","ID"="idaho","IL"="illinois","IN"="indiana","KS"="kansas","KY"="kentucky","LA"="louisiana","MA"="massachussets","MD"="maryland","ME"="maine","MN"="minnesota","MI"="michigan","MS"="mississippi","MS"="mississippi","MO"="missouri","MT"="montana","NE"="north carolina","ND"="north dakota","NH"="new hampshire","NJ"="new jersey","NM"="new mexico","NV"="nevada","NY"="new york","OH"="ohio","OK"="oklahoma","OR"="oregon","PA"="pennsylvania","SC"="south carolina","SD"="south dakota","TN"="tennessee","TX"="texas","UT"="utah","VA"="virginia","WA"="washington","WI"="wisconsin","WY"="wyoming"))

最佳答案

如果我们可以使用内置的 state.name 会更容易和 state.abb

df1$state <- with(df1, tolower(setNames(state.name, state.abb)[state]))

使用 OP 的数据集
zipcode_new$state <- with(zipcode_new, tolower(setNames(state.name, 
state.abb)[state]))

数据
set.seed(24)
df1 <- data.frame(state = sample(state.abb, 100, replace = TRUE),
stringsAsFactors = FALSE)

关于重命名数据框中的观察,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59130419/

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