如何创建仅包含整数的 table
How to create a table with only integers
我有一个 table 样本,其中包含分类法 [chr] 和 presence/absebce 数据 [num]。我从 .tsv 文件导入它。它是具有 x 个观测值和 y 个变量的 table。我必须将它转换为 table,仅以整数作为条目。
我尝试了 lapply(data,as.integer)
,它适用于具有 presence/absence 数据的列,但在分类列中,我的数据消失了,我有 NA 而不是物种。更重要的是,我不再有 table,而是一个包含 y 个变量的列表。
还有其他方法吗?
taxonomy
site1
site2
site3
site4
species1
0
1
0
0
species2
1
0
0
0
species3
0
1
1
1
在 lapply(data,as.integer)
之后看起来像这样:
taxonomy
site1
site2
site3
site4
NA
0
1
0
0
NA
1
0
0
0
NA
0
1
1
1
使用dplyr
,您可以...
library(dplyr)
# everything except the first column
mtcars %>%
mutate(across(-1, as.integer))
# everything except "taxonomy"
mtcars %>%
mutate(across(-taxonomy, as.integer))
# everything that starts with "site"
data %>%
mutate(across(starts_with("site"), as.integer))
我首先质疑您的数据中有什么内容可以将其读取为字符。我的猜测是有一些“NA”字符。如果您使用 read.table()
,您可能需要调整参数 na.strings = "NA"
以首先将其作为整数读入。
如果我们想使用 base R,我们可以使用 lapply 并将输出分配给数据的一个子集:
data[-1]<-lapply(data[-1], as.integer)
data
我想我现在知道问题出在哪里了 - 我需要在我的 table.
中使用分类名称作为标签制作第一列
使用 read.csv('data.csv', header = TRUE, row.names = 1)
读取数据实际上有所帮助。
我有一个 table 样本,其中包含分类法 [chr] 和 presence/absebce 数据 [num]。我从 .tsv 文件导入它。它是具有 x 个观测值和 y 个变量的 table。我必须将它转换为 table,仅以整数作为条目。
我尝试了 lapply(data,as.integer)
,它适用于具有 presence/absence 数据的列,但在分类列中,我的数据消失了,我有 NA 而不是物种。更重要的是,我不再有 table,而是一个包含 y 个变量的列表。
还有其他方法吗?
taxonomy | site1 | site2 | site3 | site4 |
---|---|---|---|---|
species1 | 0 | 1 | 0 | 0 |
species2 | 1 | 0 | 0 | 0 |
species3 | 0 | 1 | 1 | 1 |
在 lapply(data,as.integer)
之后看起来像这样:
taxonomy | site1 | site2 | site3 | site4 |
---|---|---|---|---|
NA | 0 | 1 | 0 | 0 |
NA | 1 | 0 | 0 | 0 |
NA | 0 | 1 | 1 | 1 |
使用dplyr
,您可以...
library(dplyr)
# everything except the first column
mtcars %>%
mutate(across(-1, as.integer))
# everything except "taxonomy"
mtcars %>%
mutate(across(-taxonomy, as.integer))
# everything that starts with "site"
data %>%
mutate(across(starts_with("site"), as.integer))
我首先质疑您的数据中有什么内容可以将其读取为字符。我的猜测是有一些“NA”字符。如果您使用 read.table()
,您可能需要调整参数 na.strings = "NA"
以首先将其作为整数读入。
如果我们想使用 base R,我们可以使用 lapply 并将输出分配给数据的一个子集:
data[-1]<-lapply(data[-1], as.integer)
data
我想我现在知道问题出在哪里了 - 我需要在我的 table.
中使用分类名称作为标签制作第一列使用 read.csv('data.csv', header = TRUE, row.names = 1)
读取数据实际上有所帮助。