1

I have a number of large data frames for which I need to know the number of elements in each row. For example, if my dataframe df looks like

X Y Z A B
Q R S

I would want the following output vector:

5
3

How can I code for this in R?

RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
Aro
  • 13
  • 2
  • 1
    That is one strange data.frame. Can you provide a sample of your data in R compatible objects? – Roman Luštrik Aug 16 '18 at 15:33
  • I would be happy to -- but I'm so new at this that I have to ask: what do you mean by "R-compatible objects"? – Aro Aug 16 '18 at 21:20
  • You're in luck. There is just the resource you need: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Roman Luštrik Aug 17 '18 at 07:15

1 Answers1

1

We can use rowSums on the non-missing elements (assuming the columns that doesn't have values are NA)

rowSums(!is.na(df))

If the values are blank "" instead of NA, then create the logical matrix with == and use rowSums

rowSums(df != "")
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    @RavinderSingh13. You can use `apply`, but should be slower i.e. `apply(!is.na(df), 1, sum)` – akrun Aug 16 '18 at 15:44
  • 1
    The values are indeed blank, and your rowSums(df != "") solution is exactly what I needed! I had tried using the rowSums function before but didn't know I could indicate blank values with "". Thank you very much! – Aro Aug 16 '18 at 21:22