You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言:将向量中元素的计数关联到数据框的匹配索引

解决方案:将向量计数匹配到数据框索引

没问题,我来帮你搞定这个需求!你已经用table(vec)得到了向量元素的计数,接下来只需要把这些计数和你的数据框df关联起来,把没匹配到的索引计数设为0就行。下面是具体的实现方法,分base R和dplyr两种方式供你选择:

方法一:使用Base R实现

首先把table生成的计数结果转换成数据框,再通过merge做左连接,最后把缺失值替换为0:

# 你的原始数据
df <- structure(list(indx = 1:10), row.names = c(NA, 10L), class = "data.frame")
vec <- c(3,5,9,9,5,4,3,3)

# 生成计数并转换为数据框
vec_counts <- table(vec)
vec_counts_df <- as.data.frame(vec_counts, stringsAsFactors = FALSE)
# 重命名列并转换索引为数值型
colnames(vec_counts_df) <- c("indx", "vec_counts")
vec_counts_df$indx <- as.numeric(vec_counts_df$indx)

# 左连接并填充0
result_df <- merge(df, vec_counts_df, by = "indx", all.x = TRUE)
result_df$vec_counts[is.na(result_df$vec_counts)] <- 0

# 查看结果
print(result_df)

运行后你会得到预期的结果:

indx vec_counts
1     1          0
2     2          0
3     3          3
4     4          1
5     5          2
6     6          0
7     7          0
8     8          0
9     9          2
10   10          0

方法二:使用dplyr包实现(更简洁)

如果你习惯用tidyverse风格的代码,可以用dplyr的left_join和mutate一步完成:

library(dplyr)

# 你的原始数据
df <- structure(list(indx = 1:10), row.names = c(NA, 10L), class = "data.frame")
vec <- c(3,5,9,9,5,4,3,3)

# 生成计数、转换数据框、关联并填充0
result_df <- df %>%
  left_join(as.data.frame(table(vec), stringsAsFactors = FALSE) %>%
              rename(indx = vec, vec_counts = Freq) %>%
              mutate(indx = as.numeric(indx)),
            by = "indx") %>%
  mutate(vec_counts = replace_na(vec_counts, 0))

# 查看结果
print(result_df)

这段代码的逻辑和base R版本一致,只是用管道操作让代码更连贯易读,最终结果完全相同。

内容的提问来源于stack exchange,提问作者locket

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 01:52:34