R更新if语句以添加计数

R update if statement to add count

我正在尝试计算列如何包含每行的文本。我有以下内容告诉我是否所有列都包含文本:

df = structure(list(Participant = 1:3, A = c("char", "foo", ""), B = c("char2", 0L, 0L)), .Names = c("Participant", "A", "B"), row.names = c(NA,                                                                                                                        -3L), class = "data.frame")

 df$newcolumn <- ifelse(nchar(df$A)>1 & nchar(df$B)>1, "yes", "no")

而不是 "Yes" 或 "No" 我想要计算发生的匹配次数。想法?

如果我们需要获取每行的 nchar,循环遍历感兴趣的列,获取 nchar,并使用 Reduce+ 来获取每行总和

df$CountNChar <- Reduce(`+`, lapply(df[-1], nchar))

或者如果我们需要逻辑条件的sum,只需将nchar更改为nchar(x) > 1(匿名函数调用)

df$CountNChar <- Reduce(`+`, lapply(df[-1], function(x) nchar(x) >1))
df$CountNChar
#[1] 2 1 0

根据您的逻辑,您可以尝试如下操作:

df$newcolumn <- (nchar(df$A)>1) + (nchar(df$B)>1)

df
  Participant    A     B newcolumn
1           1 char char2         2
2           2  foo     0         1
3           3          0         0

您似乎在计算 df$Adf$B 中包含多个字符的行数。最简单的方法是使用 sum,因为 logical 向量可以像 numericinteger 一样相加。因此,你想要的代码片段是

sum(nchar(df$A)>1 & nchar(df$B)>1)

但是,看你的第一句话,你应该知道数据框的一列中只能存在一种类型的数据。 c("foo",0L,0L) 是 class "character" 的向量,元素为 "foo","0","0".