lmcshane
lmcshane

Reputation: 1114

R update if statement to add count

I'm trying to count how columns contain text per row. I have the following that tells me if all columns contain text:

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")

Instead of "Yes" or "No" I want a count of how many matches occur. Ideas?

Upvotes: 1

Views: 319

Answers (3)

JDL
JDL

Reputation: 1654

You appear to be trying to count the number of rows wheredf$A and df$B have more than one character in them. The easiest way to do this is with sum, since logical vectors can be added up just like numeric or integer. Thus, the code fragment you want is

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

However, looking at your first sentence, you should be aware that only one type of data can exist in a column of a data frame. c("foo",0L,0L) is a vector of class "character", with elements "foo","0","0".

Upvotes: 1

Sandipan Dey
Sandipan Dey

Reputation: 23129

Using your logic you can try something like the following:

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

Upvotes: 1

akrun
akrun

Reputation: 887851

If we need to get the nchar per row, loop through the columns of interest, get the nchar, and use Reduce with + to get the sum per each row

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

Or if we need the sum of logical condition, just change the nchar to nchar(x) > 1 (with anonymous function call)

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

Upvotes: 1

Related Questions