gpt4 book ai didi

r - 如何在 R Statistics 中的数字字符串中粘贴逗号 (,)?

转载 作者:行者123 更新时间:2023-12-02 02:06:50 25 4
gpt4 key购买 nike

我是 R 统计方面的新手。我有一个内部有多个对象(数字)的向量,我想在整个对象的第一个和第二个数字之间放置一个逗号。

x 给出以下结果:

  [8] -8196110 -7681989 -8042092 -8196660 -7606310 -7217828 -7634887
[15] -7401244 -7211947 -7636932 -7606444 -7598894 -7398965```

My question is how to automatically put a comma in all those objects between the first and the second numbers. The desired output would be:

```[1] -8,385772 -7,390682 -8,019960 -8,300000 -8,069984 -8,786782 -7,414995
[8] -8,196110 -7,681989 -8,042092 -8,196660 -7,606310 -7,217828 -7,634887
[15] -7,401244 -7,211947 -7,636932 -7,606444 -7,598894 -7,398965```

最佳答案

我们可以使用 sub 捕获字符串开头 (^) 的第一个数字,并替换为反向引用 (\\1) 后跟,

sub("^(-?\\d)", "\\1,", x)

-输出

[1] "-8,196110" "-7,681989" "-8,042092" "-8,196660" "-7,606310" "-7,217828" "-7,634887" "-7,401244" "-7,211947" "-7,636932" "-7,606444" "-7,598894" "-7,398965"

数据

x <- c(-8196110, -7681989, -8042092, -8196660, -7606310, -7217828, 
-7634887, -7401244, -7211947, -7636932, -7606444, -7598894, -7398965
)

关于r - 如何在 R Statistics 中的数字字符串中粘贴逗号 (,)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68320808/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com