字符的 ColSum

ColSum of Characters

我想创建一个总计列来计算包含字符值的特定行中的单元格数。这些值只会是 3 个不同字母(R 或 B 或 D)中的一个。因此,使用下面脚本中的示例,结果将是:p1=2、p2=1p3=2p4=1p5=1

我在考虑使用带条件的 nrow 是可行的方法,但我无法让它发挥作用。像这样:

# count the number of columns where the cell is not blank (or contains an R,B,D)
test$tot <- nrow(!test="") 

非常感谢任何帮助!

---------------- 参考脚本:

  column1 <- c("p1","p2","p3","p4","p5")
  column2 <- c("R","","R","R","")
  column3 <- c("","B","","","B")
  column4 <- c("D","","D","","")
  test <- data.frame(column1,column2,column3,column4)
  colnames(test)[c(1:4)] <- c("pol_nbr","r1","r2","r3")
  View(test)

将因子转换为字符并使用 nzchar():

test <- data.frame(column1, column2, column3, column4, stringsAsFactors = FALSE)

test$ne <- rowSums(apply(test[-1], 2, nzchar))
test
  column1 column2 column3 column4 ne
1      p1       R               D  2
2      p2               B          1
3      p3       R               D  2
4      p4       R                  1
5      p5               B          1

使用rowSums:

test$tot_cols <- rowSums(test[, -1] != "")