【问题标题】:Creating a column that counts how many times a variable appears across the columns in R创建一个列来计算变量在 R 中的列中出现的次数
【发布时间】:2022-11-04 00:01:07
【问题描述】:

假设我有这个数据集:

  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  

我将如何创建一个列来计算“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

【问题讨论】:

    标签: r


    【解决方案1】:

    我们可能会使用

    df1[paste0("count_", seq_along(df1))] <- lapply(1:2, 
         function(x) rowSums(df1 == x))
    

    -输出

    > df1
      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
    

    数据

    df1 <- structure(list(col1 = c(2L, 1L, 1L, 1L, 1L, 1L, 2L, 2L), col2 = c(1L, 
    1L, 2L, 2L, 2L, 1L, 1L, 2L)), class = "data.frame",
     row.names = c("1", 
    "2", "3", "4", "5", "6", "7", "8"))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-03
      • 2016-07-27
      • 1970-01-01
      • 2021-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多