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 - Fatal编程技术网

R 如何创建此热图的矩阵?

R 如何创建此热图的矩阵?,r,R,我有 我想创建一个热图,其中显示所有玩家每条消息的消息密度。我想将其限制为x轴上的0-14个消息值(换句话说,我关心John有20个消息值,这应该会影响总体密度,但我不想看到x轴上列出20个消息值,因为这种情况并不经常发生)。球员姓名在y轴上。我该怎么做?如果这不合理,请告诉我。如果我理解正确,您可能根本不需要将数据转换为矩阵,如果您愿意使用ggplot2中的geom\u tile: Person,Messages Dave,8 James,6 Dave,6 Dave,8 Dave,8 John

我有


我想创建一个热图,其中显示所有玩家每条消息的消息密度。我想将其限制为x轴上的0-14个消息值(换句话说,我关心John有20个消息值,这应该会影响总体密度,但我不想看到x轴上列出20个消息值,因为这种情况并不经常发生)。球员姓名在y轴上。我该怎么做?如果这不合理,请告诉我。

如果我理解正确,您可能根本不需要将数据转换为矩阵,如果您愿意使用
ggplot2
中的
geom\u tile

Person,Messages
Dave,8
James,6
Dave,6
Dave,8
Dave,8
John,5
John,5
John,20
Dave,0
....
dat <- read.table(textConnection("Person,Messages
Dave,8
James,6
Dave,6
Dave,8
Dave,8
John,5
John,5
John,20
Dave,0"),sep = ",",header = TRUE)


dat <- ddply(dat,.(Person,Messages),summarise,val = length(Person))
ggplot(dat,aes(x = Messages, y = Person, fill = val)) + 
        geom_tile()
#Some data to pad with the missing combinations
pad <- expand.grid(unique(dat$Person),
                    min(dat$Messages):max(dat$Messages))
colnames(pad) <- c('Person','Messages')

#Aggregate the data and merge with pad data
dat <- ddply(dat,.(Person,Messages),summarise,val = length(Person))
tmp <- merge(dat,pad,all.y = TRUE)

#Convert from long to wide
rs <- cast(tmp,Person~Messages,value = 'val')

#Clean up the result
rownames(rs) <- rs$Person
rs <- rs[,-1]
rs[is.na(rs)] <- 0

> rs
      0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
Dave  1 0 0 0 0 0 1 0 3 0  0  0  0  0  0  0  0  0  0  0  0
James 0 0 0 0 0 0 1 0 0 0  0  0  0  0  0  0  0  0  0  0  0
John  0 0 0 0 0 2 0 0 0 0  0  0  0  0  0  0  0  0  0  0  1