最优雅的方式加载csv与点作为千位分隔符在R

最优雅的方式加载csv与点作为千位分隔符在R

本文介绍了最优雅的方式加载csv与点作为千位分隔符在R的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:据我所知,这个问题不是重复的!我发现的所有任务/答案都是如何消除已经在R中的数据中的点,或如何在加载时将小数点改为逗号。

NB: To the best of my knowledge this question is not a duplicate! All the questios/answers I found are either how to eliminate points from data that are already in R or how to change the decimal point to a comma when loading it.

我有一个csv,数字如: 4.123,98 。问题是,由于的输出成为一个字符串矩阵加载 read.table read.csv read.csv2 。将 dec 更改为不起作用。

I have a csv with numbers like: 4.123,98. The problem is that because of the . the output becomes a character string matrix when loading with read.table, read.csv or read.csv2. Changing dec to , doesn't help.

我的问题

什么是最优雅的方式加载此csv,以便数字变成例如 4123.98 为数字?

推荐答案

#some sample data
write.csv(data.frame(a=c("1.234,56","1.234,56"),
                     b=c("1.234,56","1.234,56")),
          "test.csv",row.names=FALSE,quote=TRUE)

#define your own numeric class
setClass('myNum')
#define conversion
setAs("character","myNum", function(from) as.numeric(gsub(",","\\.",gsub("\\.","",from))))

#read data with custom colClasses
read_data=read.csv("test.csv",stringsAsFactors=FALSE,colClasses=c("myNum","myNum"))
#let's try whether this is really a numeric
read_data[1,1]*2

#[1] 2469.12

这篇关于最优雅的方式加载csv与点作为千位分隔符在R的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 08:53