vj.vijay
vj.vijay

Reputation: 25

Count a value in a column in a data frame in R programming

Hi my data looks like below:

Product Price Quantity Returns 
Fridge  $260  20       3 
Oven    $150  12       #N/A 
Iron    $100  #N/A     5 
Stove   $150  20       #N/A

I want R to return the number of times "#N/A" appears in the column Returns.

Thanks for the help. I'm new to R and trying to self teach.

Upvotes: 2

Views: 6157

Answers (4)

Braj
Braj

Reputation: 1

Store your dataframe in variable x, whose 4th column is Returns and you want to count the number of #NA.

Run the command on R console as:

table(is.na(x[,4]))

and take the value of TRUE

Upvotes: 0

DJack
DJack

Reputation: 4940

Returns<- subset(df, df$Returns=="#N/A")
nrow(Returns)

Upvotes: 0

juba
juba

Reputation: 49053

You can apply table to your Returns column :

table(df$Returns)

You can then display a specific value this way :

tab <- table(df$Returns)
tab["#N/A"]

Upvotes: 1

Paul Hiemstra
Paul Hiemstra

Reputation: 60984

df$Returns[df$Returns == "#N/A"] <- NA
sum(is.na(df$Returns))

should do the trick. It first checks which values of df$Returns are NA. Next we use the fact that in sum TRUE is interpreted as 1 and FALSE as 0 to get the total number of NA's.

Upvotes: 4

Related Questions