如何在R中对同一列同时实现K转千、M转百万的单位转换与数值化
问题原因
你两次替换操作都是直接读取原始的Release Clause列作为输入,第二次替换M的操作没有用到第一次替换K后的结果,所以直接覆盖了第一次的输出。
解决方案
方法1:链式替换(修改原有代码)
将第二次替换的输入改为第一次操作生成的Release_Clause2列即可:
library(stringr) # 先替换K单位 fifa$Release_Clause2 = str_replace(fifa$`Release Clause`,"K","000") # 基于替换完K的结果替换M单位 fifa$Release_Clause2 = str_replace(fifa$Release_Clause2,"M","000000") # 转换为数值类型 fifa$Release_Clause2 = as.numeric(fifa$Release_Clause2)
方法2:批量替换(更简洁高效)
用str_replace_all传入命名向量一次性完成所有单位替换,不需要分步写:
library(stringr) fifa$Release_Clause2 = as.numeric( str_replace_all(fifa$`Release Clause`, c("K" = "000", "M" = "000000")) )
额外注意
如果你的原始Release Clause列包含€等货币符号,转换数值会生成NA,需要先移除符号再处理:
library(stringr) fifa$Release_Clause2 = as.numeric( str_replace_all( str_remove(fifa$`Release Clause`, "€"), c("K" = "000", "M" = "000000") ) )
内容的提问来源于stack exchange,提问作者JME19
相关产品推荐
相关产品推荐

