2013-07-14 85 views
0

我有一个包含两个变量(数据点)的文本文件 - 第一个变量用于学生ID,第二个变量包含一组用于每个学生ID。如何将文本文件加载到R,其中列包含用逗号分隔的数据点

格式student_id数据,{等级}

例如:

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 

I tri ED以下命令将数据加载成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 

我会很感激的任何帮助,如何去这个问题。请让我知道你是否希望我提供更多信息。谢谢!

+0

问题没有明确定义。每个学生有多少等级? – agstudy

+0

如果学生之间只有逗号隔开,你应该如何区分成绩和学生ID?每个学生的成绩不一定等级?我甚至没有用R代码来谈论,只是试图解释看看你的示例数据的人如何知道哪个是哪个。 – Marius

+0

我会使用'readLines',然后在逗号上使用'strsplit'。将第一个之后的所有内容填入列表中。问题是,你不能有一个data.frame每行不同的列数... – Justin

回答

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) 
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   
+0

res [, - ncol(res)]'可能比你的最后一个例子更透明... –

+0

@BenBolker谢谢!我编辑我的答案! – agstudy

相关问题