1

给定以下数据(myinput.txt):

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

2 回答 2

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)
于 2013-02-15T04:22:08.353 回答
0

使用一些readLines strsplit和正则表达式来说明从一开始就破坏名称:

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"
于 2013-02-15T05:06:52.710 回答