我想推断一个角色报告的信息,见下文:
X<- c("BB", "BB", "CC", "CC", "CC", "EE", "EE")
names(X) <- c(1, 2, 2, 2, 3, 3, 4)
字符如下:
X
1 2 2 2 3 3 4
"BB" "BB" "CC" "CC" "CC" "EE" "EE"
位置2中的 "CC"
出现两次,此信息应由行Time
报告预期输出:
1 2 2 3 3 4 # Position
1 1 2 1 1 1 # Times
"BB" "BB" "CC" "CC" "EE" "EE" # Character
尝试:
table (names(X))
data.frame(X)
答案 0 :(得分:2)
我们可以在“X”的names
上使用“X”的值进行分组操作并获取频率
library(data.table)
data.table(X, nm = names(X))[, .N, .(X, nm)]
# X nm N
#1: BB 1 1
#2: BB 2 1
#3: CC 2 2
#4: CC 3 1
#5: EE 3 1
#6: EE 4 1
或tidyverse
library(dplyr)
data_frame(X, nm = names(X)) %>%
count(X, nm)
或aggregate
base R
aggregate(cbind(n = rep(1, length(X))) ~ X + names(X), FUN = sum)