lundi 18 février 2019

How to count observations when it meets with a specific condition in R

I have data like this.

 a=c(rep("1",3), rep("2",3))
 b=c("usa", "usa", "france", "italy","Spain", "Germany")
 c<-c("usa","france", "italy","Spain", "Germany", "uk")
 data<-data.frame(a,b,c)
 data
  a       b       c
1 1     usa     usa
2 1     usa  france
3 1  france   italy
4 2   italy   Spain
5 2   Spain Germany
6 2 Germany      uk

I tried to write following code. But it gives me following error: Error in length(c != b, by = a) : 2 arguments passed to 'length' which requires 1

The code is:

 for(i in 1:nrow(data)){
   x= length(c!=b, by=a)
 }

My goal is to count different countries in column "c" if they are different from countries in "b" which will be calculated in each group in column "a". It should be counted only in case, if they are different than countries in c column. So could you help me to correct this error in this code?

Aucun commentaire:

Enregistrer un commentaire