R中的十进制列作为字符串而不是小数

时间:2013-11-25 18:39:42

标签: r csv

这是我的CSV文件:

"Product","Total","Destrio","TotDestrio","Percent"
ANGELLE DIRECT,60904,0,60904,0
CHERRY AMARILLO,60538,9071,69609,13.0313608872
CHERRY AMARILLO PER,20486,5042,25528,19.7508617988
CHERRY EN RAMA,186055,31826,217881,14.6070561453

所以我用这个:

prod <- read.csv("file.csv",header=T)
prod$Percent <- as.numeric(prod$Percent)
prod$Percent <- factor(prod$Percent, levels =
                         unique(prod[order(prod$Percent),"Percent"]))

prod$Percent <- as.numeric(prod$Percent)未转换为数字,prod$Percent <- factor(prod$Percent, levels =unique(prod[order(prod$Percent),"Percent"]))未按此字段排序Percent

我需要Percent为小数,而不是字符串,并按此字段按降序排列。

1 个答案:

答案 0 :(得分:1)

您阅读了CSV,一切都很好。 “百分比”列是数字。然后你按它订购。实际上就是这样。

> prod <- read.csv("f:\\temp\\test.csv",header=T)

> str(prod)
'data.frame':   4 obs. of  5 variables:
 $ Product   : chr  "ANGELLE DIRECT" "CHERRY AMARILLO" "CHERRY AMARILLO PER" "CHERRY EN RAMA"
 $ Total     : int  60904 60538 20486 186055
 $ Destrio   : int  0 9071 5042 31826
 $ TotDestrio: int  60904 69609 25528 217881
 $ Percent   : num  0 13 19.8 14.6

> sum(prod$Percent)
 [1] 47.38928

> prod[order(prod$Percent),]
              Product  Total Destrio TotDestrio  Percent
1      ANGELLE DIRECT  60904       0      60904  0.00000
2     CHERRY AMARILLO  60538    9071      69609 13.03136
4      CHERRY EN RAMA 186055   31826     217881 14.60706
3 CHERRY AMARILLO PER  20486    5042      25528 19.75086