r - 仅更改 R 中分类列中的某些值

标签 r dataframe dplyr

假设我有 df像这样:

df <- tribble(
  ~Country, 
  "Bangladesh", 
  "India", 
  "Nigeria", 
  "China", 
  "France", 
  "Canada", 
)

我只想更改一些名称,而不是全部。例如,只有中国和法国。我尝试了下面的代码,但它取代了其余的 NA。

shortNames = c("China" = "CHN", "France" = "FR")
df$Country <- shortNames[df$Country]

最佳答案

您需要排除 shortNames 中没有的名称。

i <- df$Country %in% names(shortNames)
df$Country[i] <- shortNames[df$Country[i]]

df
#  Country   
#  <chr>     
#1 Bangladesh
#2 India     
#3 Nigeria   
#4 CHN       
#5 FR        
#6 Canada    

关于r - 仅更改 R 中分类列中的某些值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75918203/

相关文章:

r - 通过正则表达式灵活分割字符串

python - Pandas 拆解专栏

python - Pandas 数据帧 : difference between all dates for each unique id

Python Camelot - 如何从表中删除换行符/n

r - 按组引导并计算统计数据

R:使用共享名称模式的多列将数据 reshape 为更长的格式

r - 如何在 `stringr` 管道中使用 `dplyr`

r - 在 R markdown HTML 文件中并排打印数字?

R根据行值将索引列添加到数据框

r - R : mle2 中的配置文件置信区间