如何计算R中数据集中某个字符的出现次数
我目前正在玩一个模拟数据集,在这个数据集中我记录了一种特定种类的花被一种蜜蜂访问的次数。我的部分数据集可能如下所示:如何计算R中数据集中某个字符的出现次数,r,character,R,Character,我目前正在玩一个模拟数据集,在这个数据集中我记录了一种特定种类的花被一种蜜蜂访问的次数。我的部分数据集可能如下所示: Plant Visitor.1 Visitor.2 Visitor.3 1 Bombus Bombus NA 2 Apis Bombus Apis 3 NA NA NA 4 Apis NA NA 5
Plant Visitor.1 Visitor.2 Visitor.3
1 Bombus Bombus NA
2 Apis Bombus Apis
3 NA NA NA
4 Apis NA NA
5 NA NA NA
6 Apis NA NA
7 Apis Apis Halictid
8 Apis Apis NA
9 Bombus Halictid Halictid
10 NA NA NA
11 NA NA NA
12 NA NA NA
13 Halictid NA NA
有没有办法让我计算一下“Bombus”、“api”、“Halictid”等词在每一列中出现的次数,或者甚至在所有三列中同时出现的次数?我已经读了很多关于如何使用数据字符串来实现这一点的书,但没有读过这样的数据集。老实说,我不太确定从哪里开始。你可以试试
library(qdapTools)
addmargins(t(mtabulate(df1[-1])),2)
# Visitor.1 Visitor.2 Visitor.3 Sum
#Apis 5 2 1 8
#Bombus 2 2 0 4
#Halictid 1 1 2 4
如果只需要整个数据集的计数
table(unlist(df1[-1]))
# Apis Bombus Halictid
# 8 4 4
我不确定你是否需要为每一行,即为每一个“工厂”这样做。那么,
Un1 <- unique(na.omit(unlist(df1[-1])))
res <- t(apply(df1[-1], 1, FUN=function(x) table(factor(x, levels=Un1))))
cbind(res, Sum=rowSums(res))
# Bombus Apis Halictid Sum
#[1,] 2 0 0 2
#[2,] 1 2 0 3
#[3,] 0 0 0 0
#[4,] 0 1 0 1
#[5,] 0 0 0 0
#[6,] 0 1 0 1
#[7,] 0 2 1 3
#[8,] 0 2 0 2
#[9,] 1 0 2 3
#[10,] 0 0 0 0
#[11,] 0 0 0 0
#[12,] 0 0 0 0
#[13,] 0 0 1 1
更新
如果需要列
(仅使用基数R)
或者是更紧凑的版本
addmargins(table(stack(df1[-1])[2:1]))
# values
#ind Apis Bombus Halictid Sum
# Visitor.1 5 2 1 8
# Visitor.2 2 2 1 5
# Visitor.3 1 0 2 3
# Sum 8 4 4 16
数据
df1如果您只需要一个简单的解决方案,请尝试将以下代码复制并粘贴到R控制台中:
## Create an artificial data set.
example.data =
data.frame(col1 = c("Bob", "Jane", "Mary"), col2 = c("Mary", "Joe", "Sam"))
## Count how many times 'x' appears in each column of the data set.
## Lets count how many times 'Bob' appears in each column.
apply(example.data, 2, function(x) length(which(x == 'Bob')))
希望有帮助:)谢谢!这很有帮助,克里斯——阿克伦,我想明天早上我会去买qdaptools和ply。它们似乎都很有帮助。唯一的一点是,我想让代码尽可能接近R提供的基本软件包——我想在离开后将成品交给实验室,而不想提醒每个人下载不同的软件包来运行程序。你认为我可以根据需要在程序中插入函数的代码,还是这不是一个好主意?我通常喜欢尽量减少使用外部软件包。
addmargins(table(stack(df1[-1])[2:1]))
# values
#ind Apis Bombus Halictid Sum
# Visitor.1 5 2 1 8
# Visitor.2 2 2 1 5
# Visitor.3 1 0 2 3
# Sum 8 4 4 16
df1 <- structure(list(Plant = 1:13, Visitor.1 = c("Bombus", "Apis",
NA, "Apis", NA, "Apis", "Apis", "Apis", "Bombus", NA, NA, NA,
"Halictid"), Visitor.2 = c("Bombus", "Bombus", NA, NA, NA, NA,
"Apis", "Apis", "Halictid", NA, NA, NA, NA), Visitor.3 = c(NA,
"Apis", NA, NA, NA, NA, "Halictid", NA, "Halictid", NA, NA, NA,
NA)), .Names = c("Plant", "Visitor.1", "Visitor.2", "Visitor.3"
), class = "data.frame", row.names = c(NA, -13L))
## Create an artificial data set.
example.data =
data.frame(col1 = c("Bob", "Jane", "Mary"), col2 = c("Mary", "Joe", "Sam"))
## Count how many times 'x' appears in each column of the data set.
## Lets count how many times 'Bob' appears in each column.
apply(example.data, 2, function(x) length(which(x == 'Bob')))