2013-02-15 46 views
1

创建一个散列数据框鉴于以下数据(myinput.txt):如何R中

A q,y,h 
B y,f,g 
C n,r,q 
### more rows 

我怎么能转换成这样的数据结构中的R?

$A 
[1] "q" "y" "h" 
$B 
[1] "y" "f" "g" 
$C 
[1] "n" "r" "q" 

回答

4

,我认为这是您的数据:

dat <- read.table(text="q,y,h 
y,f,g 
n,r,q", header=FALSE, sep=",", row.names=c("A", "B", "C")) 

如果你想要一个自动的方法:

as.list(as.data.frame((t(dat)), stringsAsFactors=FALSE)) 

## $A 
## [1] "q" "y" "h" 
## 
## $B 
## [1] "y" "f" "g" 
## 
## $C 
## [1] "n" "r" "q" 

另一对夫妇的方法,其工作是:

lapply(apply(dat, 1, list), "[[", 1) 

unlist(apply(dat, 1, list), recursive=FALSE) 
+0

@塞巴斯蒂安 - C:非常感谢。有没有办法让'dat'自动识别row.names? 即不分配它。 – neversaint 2013-02-15 04:41:09

+0

@neversaint我只是这样做,重新创建您的数据。我应该使用'row.names = 1',所以一个例子是:'read.csv(“dat.csv”,row.names = 1)'。您可能还想将'colClasses =“字符”'或'stringsAsFactors = FALSE'添加到'read.table'中。 – 2013-02-15 04:45:56

0

使用位的readLinesstrsplit和正则表达式来解释打破了名关开始:

dat <- readLines(textConnection("A q,y,h 
B y,f,g 
C n,r,q")) 

result <- lapply(strsplit(dat,"\\s{2}|,"),function(x) x[2:length(x)]) 
names(result) <- gsub("^(.+)\\s{2}.+$","\\1",dat) 

> result 
$A 
[1] "q" "y" "h" 

$B 
[1] "y" "f" "g" 

$C 
[1] "n" "r" "q" 

或用更少的正则表达式和更多的步骤:

result <- strsplit(dat,"\\s{2}|,") 
names(result) <- lapply(result,"[",1) 
result <- lapply(result,function(x) x[2:length(x)]) 

> result 
$A 
[1] "q" "y" "h" 

$B 
[1] "y" "f" "g" 

$C 
[1] "n" "r" "q"