英文:
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:
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:
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 trunc
ate.
trunc(x/1e4)
# [1] 284699 284699 284700
or
as.character(trunc(x/1e4))
# [1] "284699" "284699" "284700"
Data:
x <- 2846999998:2847000000
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论