R中的共发生图

编程入门 行业动态 更新时间:2024-10-10 17:33:51
本文介绍了R中的共发生图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我对 R 非常陌生.我有一个看起来像

I'm very very new to R. I have a csv file that looks like

A B C D A1 a v a A2 v v a A3 a a a

我想用它制作一个 co 发生图,但是当输入有字符而不是数字时,我不知道如何绘制它.

I'd like to make a co occurrence plot using it but I couldn't figure out how to plot it when the input has characters and not numbers.

我尝试使用几个包(我无法让其中任何一个工作),其中一个是 cooccur.它给了我以下错误 rowSums(spp_site_mat, na.rm = T) 中的错误:'x' 必须是数字".如果您向我指出任何有用的东西或提供任何代码建议,我将非常感激.

I tried using a few packages (I couldn't get any of them to work), out of which one is cooccur. It gave me the following error "Error in rowSums(spp_site_mat, na.rm = T) : 'x' must be numeric". I'd really really appreciate if you point me toward anything helpful or give any code suggestions.

行将具有来自 A 列的值,列将是它们对应的值,a"和v"如下所示 链接.

Rows would have the values from column A, columns would be their corresponding values, "a" and "v" something as shown in this link.

此外,我有数百列,因此我无法使用 as.numeric(table$B)

Also I have hundreds of columns so I cannot change each column to numeric using as.numeric(table$B)

推荐答案

您可以table每一行来计算唯一值,然后使用 rbind.fill.然后,您可以使用 geom_tile 添加计数作为标签进行绘图.

You can table each row to count the unique values and then form a matrix using use rbind.fill. You can then plot using geom_tile adding in the counts as labels.

# your data dat <- read.table(text="A B C D A1 a v a A2 v v a A3 a a a", header=TRUE) library(plyr) library(ggplot2) library(reshape2) # transform your data mat <- rbind.fill.matrix(apply(dat[-1], 1, function(i) t(as.matrix(table(i))))) mat[is.na(mat)] <- 0 rownames(mat) <- dat$A # plot ggplot(melt(mat), aes(Var2, Var1, fill=value)) + geom_tile() + scale_fill_gradient(limits=c(0,3), low="white") + geom_text( aes(label=value))

编辑

关于代码

mat <- rbind.fill.matrix(apply(dat[-1], 1, function(i) t(as.matrix(table(i)))))

从内部开始

apply(dat[-1], 1, function(i) t(as.matrix(table(i))))

apply with MARGIN = 1 将函数应用于数据行,不包括第一列.该函数的目的是为每一行列出值.as.matrix 用于改变输出的格式,t(转置)改变矩阵的方向.(很可能是一种更简洁的方法)

apply with MARGIN = 1 applies the function across the rows of the data, excluding the first column. The aim of the function is to table the values for each row. as.matrix is used to change the format of the output and the t (transpose) changes the orientation of the matrix. (Most likely a more succinct way to do this)

由于每行中可能没有相同的值(第 3 行没有 v)所有值都不会在每个表中表示 - 所以 rbind 将不起作用.来自 plyr 包的 rbind.fill 用 NA 填充.

As there may not be the same values in each row (row 3 has no v's) all values will not be represented in each table - so rbind will not work. rbind.fill from plyr package fills in with NA.

下面用零替换缺失的 (NA)

Below replaces the missing (NA) with zero

mat[is.na(mat)] <- 0

更多推荐

R中的共发生图

本文发布于:2023-07-18 14:23:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1145674.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:发生

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!