【问题标题】:How to load a text file into R where a column contains data points separated by comma如何将文本文件加载到 R 中,其中列包含用逗号分隔的数据点
【发布时间】:2013-07-12 18:06:33
【问题描述】:

我有一个包含两个变量(数据点)的文本文件 - 第一个变量用于学生 ID,第二个变量包含每个学生 ID 的一组成绩。

格式为 student_id,{grades}

例如:

0,80,1001,65,71,402,99,50,03,904

表示

  student_id=0 has grades{80,100} 
  student_id=2 has grades{65,71,40} and so on.

我想在R中得到一个数据框如下

student_id   grades   
0            80,100 
1            65,71,40 
2            99,50,0 
3            90 
4

我尝试了以下命令将数据加载到 R

x <- read.delim(file, header=TRUE, row.names=NULL)

这就是我的结局

    student_id. .grades.
1              0,80,100 
2              1,65,71,40 
3              2,99,50,0 
4              3,90 
5              4

对于如何解决此问题的任何帮助,我将不胜感激。如果您希望我提供更多信息,请告诉我。谢谢!

【问题讨论】:

  • 问题没有很好的定义。每个学生有多少个年级?
  • 如果他们都只是用逗号分隔,你应该如何区分成绩和学生证,并且每个学生的成绩不一定相同?我什至不是在谈论 R 代码,只是尝试解释一下查看您的示例数据的人如何知道哪个是哪个。
  • 我会使用readLines,然后在逗号上使用strsplit。将第一个之后的所有内容都放入列表中。问题是您不能拥有每行列数不同的 data.frame...
  • 当然我在这里错过了一些东西,但是这条线在你的例子中做了什么:0,80,1001,65,71,402,99,50,03,904?
  • PS 如果read.delim 为 OP 工作,那么在原始文件中确实存在换行符和制表符分隔符,这是最初的示例搞砸了。

标签: r


【解决方案1】:

这有点棘手,因为它混合了空格和逗号分隔。我的解决方案有点难看——也许有人会想出更好的办法。

x <- readLines(textConnection(
"student_id   grades   
0            80,100 
1            65,71,40 
2            99,50,0 
3            90 
4"))

padNA <- function(x,maxLen) {
    if ((L <- (maxLen-length(x)))>0) x <- c(x,rep(NA,L))
    x
}
getPos <- function(x,n) if (length(x)>=n) x[[n]] else ""
## separate student IDs
student_id <- sapply(strsplit(x[-1],"\\s+"),getPos,1)
## (convert to numeric if you want)
## separate scores
scores <- sapply(strsplit(x[-1],"\\s+"),getPos,2)
## split scores by comma and pad to max length
scoreMat <- do.call(rbind,lapply(strsplit(scores,","),padNA,5))
## convert from character to numeric
storage.mode(scoreMat) <- "numeric"
## combine
data.frame(student_id,scoreMat)

【讨论】:

    【解决方案2】:

    我不明白您输入的问题到底是什么。但在这里我假设你有这样的东西:

    x <- readLines(textConnection(
    "student_id   grades   
    0            80,100 
    1            65,71,40 
    2            99,50,0 
    3            90 
    4"))
    

    然后在用| 替换所有空格后像这样使用read.table 并将其用作常规分隔符:

       res <- read.table(text=gsub('\\s+','|',x),sep='|',header=TRUE,fill=TRUE)
    

    你得到这张桌子:

      student_id   grades  X
    1          0   80,100 NA
    2          1 65,71,40 NA
    3          2  99,50,0 NA
    4          3       90 NA
    5          4          NA
    

    当然,像这样删除最后一列很容易:

    res[,-ncol(res)]
      student_id   grades
    1          0   80,100
    2          1 65,71,40
    3          2  99,50,0
    4          3       90
    5          4         
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-16
      • 1970-01-01
      • 2021-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多