【问题标题】:calculate max length of each field in csv file计算csv文件中每个字段的最大长度
【发布时间】:2015-06-08 02:30:45
【问题描述】:

我有一个 groovy 脚本,它遍历 csv 并将每个字段的最大长度存储在文件中:

def csv = new File('./myfile.csv').text

def max = [ ] as ArrayList

csv.eachLine { line, count ->

    def params = line.split(',')

    // skip the header line
    if (count > 0) 
    {
        params.eachWithIndex() { p, index ->        
            if (p.length() > max[index] ) {
                max[index] = p.length()
            }
        }
     }
}
println "Max length of fields: ${max}"

我想使用 R 实现相同的目标,最好使用库函数。

如何打印 csv 文件中字段的最大长度?

示例输入:

foo,bar
abcd,12345
def,234567

输出:

Max length of fields: [4, 6]

【问题讨论】:

  • 可能类似于sapply(df, function(x) max(nchar(as.character(x))))(如果df 是您的输入数据)
  • 哦,顺便说一句,你什么都不知道,克里斯·斯诺;P
  • 有趣的评论 David Arenburg :)

标签: r csv


【解决方案1】:

将数据读入数据框中,并在其列中应用指定的函数。如果数据在文件中,请将text = Lines 替换为file = "myfile.csv"。请参阅?read.csv 了解可能需要也可能不需要的其他参数,具体取决于您的真实文件的外观。

# test data
Lines <- "foo,bar
abcd,12345
def,234567"

DF <- read.csv(text = Lines, colClasses = "character")
sapply(DF, function(x) max(nchar(x)))

给予:

foo bar 
  4   6 

注意:一个潜在的问题是如果你有这样的输入。幸运的是,这个答案是正确的:

Lines <- "foo,bar
abcd,1234567e9
def,234567"

【讨论】:

    【解决方案2】:

    根据我的经验,最快的方法是使用data.table 中的fread 函数来读取文件,那么它与格洛腾迪克的答案相同

    file_path <- './myfile.csv'
    dt <- fread(file_path, colClasses = "character")
    sapply(dt, function(x) max(nchar(x)))
    

    【讨论】:

    • 这应该是一个评论,最多。
    猜你喜欢
    • 2018-04-11
    • 1970-01-01
    • 2011-06-07
    • 1970-01-01
    • 1970-01-01
    • 2014-08-31
    • 2015-04-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多