Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在R中创建哈希数据帧_R_Dataframe - Fatal编程技术网

如何在R中创建哈希数据帧

如何在R中创建哈希数据帧,r,dataframe,R,Dataframe,给定以下数据(myinput.txt): 如何在R中将其转换为这样的数据结构 $A [1] "q" "y" "h" $B [1] "y" "f" "g" $C [1] "n" "r" "q" 我假设这是您的数据: dat <- read.table(text="q,y,h y,f,g n,r,q", header=FALSE, sep=",", row.names=c("A", "B", "C")) 另两种有效的方法是: lapply(apply(dat, 1, list),

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

如何在R中将其转换为这样的数据结构

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

我假设这是您的数据:

dat <- read.table(text="q,y,h
y,f,g
n,r,q", header=FALSE, sep=",", row.names=c("A", "B", "C"))
另两种有效的方法是:

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

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

我假设这是您的数据:

dat <- read.table(text="q,y,h
y,f,g
n,r,q", header=FALSE, sep=",", row.names=c("A", "B", "C"))
另两种有效的方法是:

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

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

使用一点
readLines
strsplit
和regex来解释从开头中断名称的原因:

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"

dat使用一点
readLines
strsplit
和regex来解释从开头中断名称的原因:

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"

dat@sebastian-c:非常感谢。有没有办法让“dat”自动识别行名?i、 e.不分配。@别画蛇添足,我这样做只是为了重新创建您的数据。我应该使用
row.names=1
,因此示例是:
read.csv(“dat.csv”,row.names=1)
。您可能还需要将
colClasses=“character”
stringsAsFactors=FALSE
添加到
read.table
@sebastian-c:非常感谢。有没有办法让“dat”自动识别行名?i、 e.不分配。@别画蛇添足,我这样做只是为了重新创建您的数据。我应该使用
row.names=1
,因此示例是:
read.csv(“dat.csv”,row.names=1)
。您可能还希望将
colClasses=“character”
stringsAsFactors=FALSE
添加到
read.table
中。