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

在R语言中创建统计变量跨列出现次数的列

解决方案

你可以用Python的pandas库或者R语言来实现这个需求,以下是具体实现方式:

原数据集

col1 col2 
1   2    1 
2   1    1 
3   1    2 
4   1    2 
5   1    2 
6   1    1 
7   2    1 
8   2    2  

需求目标

新增count_1和count_2列,分别统计每行中数值1和2的出现次数,得到如下结果:

col1 col2 count_1 count_2
1   2    1     1      1
2   1    1     2      0
3   1    2     1      1
4   1    2     1      1
5   1    2     1      1
6   1    1     2      0
7   2    1     1      1
8   2    2     0      2

方法一:Python pandas

利用向量化操作实现高效统计,避免循环:

import pandas as pd

# 创建原数据集
data = {
    'col1': [2, 1, 1, 1, 1, 1, 2, 2],
    'col2': [1, 1, 2, 2, 2, 1, 1, 2]
}
df = pd.DataFrame(data)

# 新增统计列
df['count_1'] = df[['col1', 'col2']].eq(1).sum(axis=1)
df['count_2'] = df[['col1', 'col2']].eq(2).sum(axis=1)

print(df)
  • eq(1)会将数据框中等于1的元素转为True,其余为False
  • sum(axis=1)按行求和,True等价于1,False等价于0,最终得到每行1的出现次数

方法二:R语言

可以用基础R或dplyr包实现:

基础R版本

# 创建原数据集
df <- data.frame(
    col1 = c(2, 1, 1, 1, 1, 1, 2, 2),
    col2 = c(1, 1, 2, 2, 2, 1, 1, 2)
)

# 新增统计列
df$count_1 <- rowSums(df == 1)
df$count_2 <- rowSums(df == 2)

print(df)

dplyr版本

library(dplyr)

df <- df %>%
    mutate(
        count_1 = rowSums(. == 1),
        count_2 = rowSums(. == 2)
    )

print(df)
  • rowSums(df == 1)直接计算每行中等于1的元素个数,原理和pandas类似

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 11:25:29