在 R 数据框中,如果我想将列值更改为另一个值,但前提是它等于 3 个不同的值
In an R dataframe, if I want to change a column value to another value, but only if it equals 3 different things
我在 R 中有一个名为 QCEW_County_Denominated 的数据框。在这个数据框中,我有一个名为 Industry 的列。每当此列的值为 [31-33]、[44-45] 或 [48-49] - 实际值 - 而不是值范围时,我想将值分别更改为 31、44 和 48。关于如何格式化这个的任何建议? R 中的 If-then 语句是我最薄弱的地方,所以我想我应该在这里问一下。
查看 case_when()
library('dplyr')
x <- data.frame(industry = rep(c("[31-33]","[44-45]","[48-49]"), each = 4))
x %>%
mutate(industry_n = case_when(.$industry == "[31-33]" ~ 31,
.$industry == "[44-45]" ~ 44,
.$industry == "[48-49]" ~ 48))
或者如果您有 dplyr
(devtools::install_github("hadley/dplyr"
) 的开发版本,您可以 运行:
x %>%
mutate(industry_n = case_when(industry == "[31-33]" ~ 31,
industry == "[44-45]" ~ 44,
industry == "[48-49]" ~ 48))
或者像这样:
df <- data.frame(Industry = rep(c("[31-33]","[44-45]","[48-49]"), each = 4), stringsAsFactors = F)
df$Industry[df$Industry=="[31-33]"] <- 31
df$Industry[df$Industry=="[44-45]"] <- 44
df$Industry[df$Industry=="[48-49]"] <- 48
Lucy的代码很理想。
但是,如果出于某种原因您不打算使用 dplyr(虽然我没有看到您不应该使用的原因),您可以使用嵌套 if 函数:
x$new <- ifelse(x$industry == "[31-33]", 31, ifelse(x$industry == "[44-45]", 44, ifelse(x$industry == "[48-49]", 48, x$industry)))
等等
我在 R 中有一个名为 QCEW_County_Denominated 的数据框。在这个数据框中,我有一个名为 Industry 的列。每当此列的值为 [31-33]、[44-45] 或 [48-49] - 实际值 - 而不是值范围时,我想将值分别更改为 31、44 和 48。关于如何格式化这个的任何建议? R 中的 If-then 语句是我最薄弱的地方,所以我想我应该在这里问一下。
查看 case_when()
library('dplyr')
x <- data.frame(industry = rep(c("[31-33]","[44-45]","[48-49]"), each = 4))
x %>%
mutate(industry_n = case_when(.$industry == "[31-33]" ~ 31,
.$industry == "[44-45]" ~ 44,
.$industry == "[48-49]" ~ 48))
或者如果您有 dplyr
(devtools::install_github("hadley/dplyr"
) 的开发版本,您可以 运行:
x %>%
mutate(industry_n = case_when(industry == "[31-33]" ~ 31,
industry == "[44-45]" ~ 44,
industry == "[48-49]" ~ 48))
或者像这样:
df <- data.frame(Industry = rep(c("[31-33]","[44-45]","[48-49]"), each = 4), stringsAsFactors = F)
df$Industry[df$Industry=="[31-33]"] <- 31
df$Industry[df$Industry=="[44-45]"] <- 44
df$Industry[df$Industry=="[48-49]"] <- 48
Lucy的代码很理想。
但是,如果出于某种原因您不打算使用 dplyr(虽然我没有看到您不应该使用的原因),您可以使用嵌套 if 函数:
x$new <- ifelse(x$industry == "[31-33]", 31, ifelse(x$industry == "[44-45]", 44, ifelse(x$industry == "[48-49]", 48, x$industry)))
等等