简体   繁体   English

根据条件替换 R 数据帧中的值

[英]Replacing a value in R data frame based on condition

I am trying to replace the word "United States" with "USA" to colour a choropleth map for a project.我正在尝试用“USA”替换“United States”这个词来为一个项目着色一个等值线 map。 This is the code I am using on my data frame:这是我在数据框上使用的代码:

country_data_map$region[country_data_map$region == "United States"] <- "USA"

tail(country_data_map,20)

but it still prints out但它仍然打印出来

    region  value
<chr>   <chr>
208 Turkmenistan    73,08
209 Turks & Caicos Is       15,67
210 Tuvalu  20,03
211 Uganda  67,83
212 Ukraine 20,34
213 United Arab Emirates    14,51
214 United Kingdom  5,16
215 United States   6,5
216 Uruguay 11,95
217 Uzbekistan  71,1
218 Vanuatu 55,16
219 Venezuela   22,2
220 Vietnam 25,95
221 Virgin Islands  8,03
222 Wallis and Futuna   
223 West Bank   19,62
224 Western Sahara  
225 Yemen   61,5
226 Zambia  88,29
227 Zimbabwe    67,69

Does anyone know what I am doing wrong?有谁知道我做错了什么?

If you're having trouble with sneaky spaces, you could do:如果您在使用偷偷摸摸的空间时遇到问题,您可以这样做:

country_data_map$region[stringr::str_detect(country_data_map$region, "United States")] <- "USA"

And that will still work if the value is " United States" or "United States " or something like that.如果值为“美国”或“美国”或类似的东西,这仍然有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM