如果 location_1
表示“埃塞俄比亚”并且年份对应于截至如果 location_1
表示“埃塞俄比亚”并且年份对应于 1993 年以后的所有年份,则包括 1992 年和“埃塞俄比亚 (1993-)”。
不幸的是,我想出的代码全部替换为“埃塞俄比亚(-1992)”,即使对于 1992 年之后的那些年也是如此。
代码如下:
if (mydata$year >= 1992) {
mydata$location_1 <- sub("Ethiopia", "Ethiopia (-1992)", mydata$location_1)
} else mydata$location_1 <- sub("Ethiopia", "Ethiopia (1993-)", mydata$location_1)
我希望根据年份将所有“埃塞俄比亚”变成“埃塞俄比亚(-1992)”或“埃塞俄比亚(1993-)”。相反,结果是所有“埃塞俄比亚”都变成了“埃塞俄比亚(-1992)”。
最佳答案
您可以替换数据子集中的列:
mydata[which(mydata$location_1=="Ethiopia" & mydata$year <= 1992),
"location1"] <- "Ethiopia (-1992)"
mydata[which(mydata$location_1=="Ethiopia" & mydata$year > 1992),
"location1"] <- "Ethiopia (1993-)"
或者使用dplyr
:
library(dplyr)
df1 %>%
mutate(location_1=case_when(location_1=="Ethiopia" & year <= 1992 ~ "Ethiopia (-1992)",
location_1=="Ethiopia" & year > 1992 ~ "Ethiopia (1993-)",
TRUE ~ location_1))
关于r - 如何根据年份用 "Ethiopia"和 "Ethiopia (-1992)"替换 "Ethiopia (1993-)",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56821790/