【问题标题】:How do I convert the big numbers in char variable to a numerical variable? [duplicate]如何将 char 变量中的大数字转换为数值变量? [复制]
【发布时间】:2019-09-01 08:29:51
【问题描述】:
>str(data$Installs)

$ 安装次数:因子 w/ 21 个级别 "","0+","1+","1,000+",..: 8 20 15 18 11 17 17 5 5 8 ...

 db$Installs = as.character(gsub("\\+", "", db$Installs))

 str(db$Installs)
  chr [1:10841] "10,000" "500,000" "5,000,000" "50,000,000" "100,000" "50,000" "50,000" "1,000,000" "1,000,000" "10,000" ...

 db$Installs = as.double(gsub(",","",db$Installs))

 str(db$Installs)
  num [1:10841] 1e+04 5e+05 5e+06 5e+07 1e+05 5e+04 5e+04 1e+06 1e+06 1e+04 ...

我想要这样的变量:

“10000”“500000”“5000000”“50000000”“100000”“50000”“50000”“1000000”“1000000”“10000”...

我试过这段代码


db$Installs.factor <- factor(db$Installs) 
db$Installs = as.character(gsub("\\+", "", db$Installs))
db$Installs = as.double(gsub(",","",db$Installs))

【问题讨论】:

  • 试试as.numeric(gsub(",", "",db$Installs,fixed=TRUE))而不是double
  • 仍然显示相同 &gt; str(db$Installs) chr [1:10841] "10,000" "500,000" "5,000,000" "50,000,000" "100,000" "50,000" "50,000" "1,000,000" "1,000"00000, " ... &gt; db$Installs = as.numeric(gsub(",", "",db$Installs,fixed=TRUE)) &gt; str(db$Installs) num [1:10841] 1e+04 5e+05 5e+06 5e+07 1e+05 5e+04 5e+04 1e+06 1e+06 1e+04 ... 我想要这样的变量:“10000”“500000”“5000000”“50000000”“100000”“50000”“50000”“1000000”“1000000”“10000”...
  • 提供一些样本数据
  • 对于这个c &lt;- c("10,000", "500,000" ,"5,000,000", "50,000,000" ,"100,000" ,"50,000" ,"50,000", "1,000,000" ,"1,000,000", "10,000"),上述解决方案有效。
  • 你得到正确的输出(根据你的str 结果)1e+0410000

标签: r database dataframe data-cleaning


【解决方案1】:

试试这个

输入-

sample <- c("10,000+" ,"500,000+", "5,000,000+", "50,000,000+" ,"100,000+", "50,000+" ,"50,000+" ,"1,000,000+" )

解决方案-

sample <- as.numeric(gsub("\\D", "", sample))

输出-

1]    10000   500000  5000000 50000000   100000    50000    50000  1000000

注意- 如果你想强制 R 不使用指数符号,那么你可以使用 -

options("scipen"=100, "digits"=4)

scipen’:整数。决定以固定或指数表示法打印数值时要应用的惩罚。正值偏向固定,负值偏向科学记数法:固定记数法将是首选,除非它比“scipen”数字更宽。

【讨论】:

  • OP 可能仍然会发现以科学计数法打印的东西,这是一个单独的问题,他们可能希望查看 here
  • &gt; db &lt;- read.csv("googleplaystore.csv") &gt; str(db$Installs) 因子 w/ 21 个级别 "","0+","1+","1,000+",..: 8 20 15 18 11 17 17 5 5 8 ... &gt; db$Installs = as.numeric(gsub("\\D", "", db$Installs)) &gt; str(db$Installs) num [1:10841] 1e+04 5e+05 5e+06 5e+07 1e+05 5e+04 5e+04 1e+06 1e+06 1e+04 ...跨度>
  • 它正在使用上述解决方案转换为数字,现在您需要通过使用@joran 提供的链接或使用options("scipen"=100, "digits"=4) 来强制r 避免指数符号
  • 是的!完成谢谢.....options("scipen"=100, "digits"=4) 它工作了。
猜你喜欢
  • 2021-06-27
  • 2015-08-29
  • 2018-07-20
  • 1970-01-01
  • 2018-04-04
  • 2014-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多