# Create new variable in R dataframe by counting values equal to or greater than 1

#### ps1993

##### New Member
Hi,

I have a dataframe in which I need to create a new column by counting all values equal to or greater than 1 occurring row-wise. I tried to use the following command:

length(which(birds[2, 3:29] > 0))

This command only returns a value for ONE row (in this case, the 2nd row).

However, I want a column that lists such values for ALL rows.

#### fitz0r

##### New Member
Here is an example with an artificial dataset:
Code:
df <- data.frame(rnorm(100), rnorm(100), rnorm(100))
df\$t <- apply(df, 1, function(a) sum(a > 0))
This first creates a data frame containing three columns with values from the standard normal distribution (for the most part between -3 and 3).

Then it creates a new column, t, which contains the number of elements in the row that are greater than 0. This works because when you sum up a bunch of true or false the true values count as one and the false values count as zero. You can dissect it a little bit by looking at the data frame before you run the apply statement:
Code:
df[50,]
df[50,] > 0
sum(df[50,] > 0)
50 indicates the row number there so you can look at different rows that way until you believe it.

Having been a beginner not too long ago I do not consider this technique obvious at all but you will get the hang of it. I hope you can see a way to apply it to your bird dataset.