提取R中行中数字频率的函数

Function to extract requencies of numbers in rows in R

我需要一个函数,它检查 df 中每行值的频率,然后检查其中一个值是否出现 6 次或更多次,如果是,则在新列中显示该值。如果不是,则在同一个新列中写入 "nope"。 在下面的示例中: 行中的值是 1、2 或 3。因此,如果值 1、2 或 3 之一在每行中出现 6 次或更多次,则以 (1,2,or3) 中的那个值为准出现在一个新的专栏中。如果 none 个值每行出现 6 次或更多次,则同一新列中的值应为 "nope"。 example

尝试使用

为每一行应用 table 函数
make_count_col <- function(x) {
  cnt <- apply(x, 1, table)
  x$newcolumn <- apply(cnt, 2, function(y) {
    if (max(y, na.rm = T) < 6)
      out <- 'nope'
    else
      out <- names(y)[which.max(y)]
    out
    })
  x
}

您的示例已复制

x <- as.data.frame(matrix(c(1, 2, 1, 2, 2, 2, 2, 2, 3,
                            2, 3, 1, 1, 3, 2, 1, 1, 3), nrow = 2, byrow = T))
colnames(x) <- paste0('svo', 1:9)
make_count_col(x)
  svo1 svo2 svo3 svo4 svo5 svo6 svo7 svo8 svo9 newcolumn
     1    2    1    2    2    2    2    2    3         2
     2    3    1    1    3    2    1    1    3      nope