使用`substr`函数在R中获取前六个字符时为什么会得到小数?

huangapple go评论65阅读模式
英文:

Why do I get decimals when I use the substr function to get the first six characters in R?

问题

我的数据框看起来像这样:

我已经使用以下函数来提取hs10变量的前6个数字:

然而,一些变量显示为带有小数点,如下所示:

是否有原因,我怎样才能获得整数部分?

谢谢。

英文:

My dataframe looks like this:

使用`substr`函数在R中获取前六个字符时为什么会得到小数?

I have used the following function to extract the first 6 numbers of the hs10 variable:

us_chn_tariffs_18$HS6 <- as.numeric(substr(as.character(us_chn_tariffs_18$hs10), 1, 6))

However, some variables have shown up with decimals as can be seen below:

使用`substr`函数在R中获取前六个字符时为什么会得到小数?

Is there a reason for this, and how can I just get whole numbers?

Thank you.

答案1

得分: 1

当转换为字符时,您保留了科学计数法中的 "e",这仅在某些数字中发生,当有6个或更多的 "0" 时,它们将被转换为科学计数法。

substr(format(h10, scientific=F), 1, 6)

这应该可以正常工作(至少在我的 R 会话中它正常工作),希望对您有所帮助!

英文:

When converting to character you are keeping the "e" from scientific notation, it happens only in some numbers for the quantity of 0's,6 or more 0's are converted to scientific notation.

substr(format(h10, scientific=F), 1,6)

That should work fine (at least in my R session it works just fine) hope it helps!

答案2

得分: 0

你可以考虑分割和截断。

trunc(x/1e4)

1 284699 284699 284700

as.character(trunc(x/1e4))

1 "284699" "284699" "284700"


数据:

x <- 2846999998:2847000000

英文:

You could consider to divide and truncate.

trunc(x/1e4)
# [1] 284699 284699 284700

or

as.character(trunc(x/1e4))
# [1] &quot;284699&quot; &quot;284699&quot; &quot;284700&quot;

Data:

x &lt;- 2846999998:2847000000

huangapple
  • 本文由 发表于 2023年2月26日 19:58:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/75571817.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定