如何将文本文件加载到R中,其中列包含以逗号分隔的数据点

时间:2013-07-14 23:09:26

标签: r

我有一个包含两个变量(数据点)的文本文件 - 第一个变量用于学生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

我很感激如何解决这个问题。如果您希望我提供更多信息,请与我们联系。谢谢!

2 个答案:

答案 0 :(得分:1)

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

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         

答案 1 :(得分:0)

这有点棘手,因为它是由空格和逗号分隔的混合体。我的解决方案有点难看 - 也许有人会想出更好的东西。

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)
相关问题