Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/67.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_Reshape - Fatal编程技术网

R 聚合数据帧后,如何将行名列表作为值获取?

R 聚合数据帧后,如何将行名列表作为值获取?,r,reshape,R,Reshape,我有一个数据帧df,如下所示: type V1 V2 1 A bla bla 2 A bla bla 3 B bloo bla 4 B bloo bla 5 C moo bloo 6 C moo bloo 目前,我通过熔化/浇铸来获得: type bla bloo moo A 4 0 0 B 2 2 0 C

我有一个数据帧df,如下所示:

    type    V1    V2
1    A    bla    bla
2    A    bla    bla
3    B    bloo    bla
4    B    bloo    bla
5    C    moo    bloo
6    C    moo    bloo
目前,我通过熔化/浇铸来获得:

type    bla    bloo    moo
A    4    0    0
B    2    2    0
C    0    2    2
使用以下命令:

library(reshape)
melted <- melt(df, id='type')
count <- function(x) { 
  length(na.omit(x))
}
casted <- cast(melted, type~value, count)
其中,bla、bloo和moo的每个值都是原始数据帧中唯一行名的列表

有人能帮忙吗?

库(Reformae2)
library(reshape2)
df <- read.table(text="type    V1    V2
1    A    bla    bla
2    A    bla    bla
3    B    bloo    bla
4    B    bloo    bla
5    C    moo    bloo
6    C    moo    bloo")

df$id <- rownames(df)

melted <- melt(df, id=c('type','id'),measure.vars=c("V1","V2"))

fun <- function(x) paste(unique(x),collapse=",") 

dcast(melted,type~value,fun,value.var="id",fill="0")

#  type bla bloo moo
#1    A 1,2    0   0
#2    B 3,4  3,4   0
#3    C   0  5,6 5,6

df次要挑剔:可能使用
fill='0'
来精确匹配OP的期望输出…?@joran Done。谢谢你的提示。
library(reshape2)
df <- read.table(text="type    V1    V2
1    A    bla    bla
2    A    bla    bla
3    B    bloo    bla
4    B    bloo    bla
5    C    moo    bloo
6    C    moo    bloo")

df$id <- rownames(df)

melted <- melt(df, id=c('type','id'),measure.vars=c("V1","V2"))

fun <- function(x) paste(unique(x),collapse=",") 

dcast(melted,type~value,fun,value.var="id",fill="0")

#  type bla bloo moo
#1    A 1,2    0   0
#2    B 3,4  3,4   0
#3    C   0  5,6 5,6