ColSum of Characters

时间:2018-06-04 13:45:41

标签: r col

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

我在考虑使用# 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)

非常感谢任何帮助!

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

class Event(models.Model):
    banner = models.ImageField('banner', upload_to='events/banners', default='events/banners/banner_padrao_eventos.png', blank=True)

2 个答案:

答案 0 :(得分:3)

使用rowSums

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

答案 1 :(得分:0)

将因子转换为字符并使用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