这是我的第一个问题,请原谅我的错误。 我有一个数据框,其中地址在一行,并有许多缺失值和几个错误。
地址
我想添加一个新字段" District",如果地址的值包含某些值,例如,如果它包含Marino,Fairview或Clontarf,则该区域应为Dublin 3。
Dublin3 <- c("Marino", "Fairview", "Clontarf")
matches <- unique (grep(paste(Dublin3,collapse="|"),
DubPPReg$Address, value=TRUE))
使用R,如何更新匹配为真的区域的值?
答案 0 :(得分:1)
# I've created example data frame with column Adress
df <- data.frame(Adress = c("Braemor Drive",
"Clontarf",
"Co.Dublin",
"Meadow Avenue",
"Dundrum",
"Philipsburgh Avenue",
"Marino",
"Myrtle Square", "The Coast"))
# And vector Dublin
Dublin3 <- c("Marino", "Fairview", "Clontarf")
# Match names in column Adress and vector Dublin 3
df$District <- ifelse(df$Adress %in% Dublin3, "Dublin 3",FALSE)
df
Adress District
1 Braemor Drive FALSE
2 Clontarf Dublin 3
3 Co.Dublin FALSE
4 Meadow Avenue FALSE
5 Dundrum FALSE
6 Philipsburgh Avenue FALSE
7 Marino Dublin 3
8 Myrtle Square FALSE
9 The Coast FALSE
而不是FALSE
您可以选择其他内容(例如NA
)。
已编辑:如果您的数据位于向量中
df <- c("Braemor Drive, Churchtown, Co.Dublin",
"Meadow Avenue, Clontarf, Dublin 14",
"Sallymount Avenue, Ranelagh", "Philipsburgh Avenue, Marino")
看起来像这样
df
[1] "Braemor Drive, Churchtown, Co.Dublin"
[2] "Meadow Avenue, Clontarf, Dublin 14"
[3] "Sallymount Avenue, Ranelagh"
[4] "Philipsburgh Avenue, Marino"
您可以使用grepl
这样的
match <- ifelse(grepl("Marino|Fairview|Clontarf", df, ignore.case = T), "Dublin 3",FALSE)
,输出
[1] "FALSE" "Dublin 3" "FALSE" "Dublin 3"
这意味着您要查找的一个或所有匹配名称(即Marino,Fairview或Clontarf)位于df
的第二和第四行。