Reading a CSV file organized horizontally

邮差的信 提交于 2019-11-27 13:16:43

Let's say your file is called 'data.csv' and it contains:

var1,1,2,3,4,5,6
var2,2.1,3.9,4.6,5.2,6.1
var3,M,F,M,F,M,M

Note var1 and var3 have 6 values but var2 has only 5. So, the idea is to read the data, transpose it and then use read.csv.

read.tcsv = function(file, header=TRUE, sep=",", ...) {

  n = max(count.fields(file, sep=sep), na.rm=TRUE)
  x = readLines(file)

  .splitvar = function(x, sep, n) {
    var = unlist(strsplit(x, split=sep))
    length(var) = n
    return(var)
  }

  x = do.call(cbind, lapply(x, .splitvar, sep=sep, n=n))
  x = apply(x, 1, paste, collapse=sep) 
  out = read.csv(text=x, sep=sep, header=header, ...)
  return(out)

}

Then, you can do:

read.tcsv("data.csv")

  var1 var2 var3
1    1  2.1    M
2    2  3.9    F
3    3  4.6    M
4    4  5.2    F
5    5  6.1    M
6    6   NA    M
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!