How to get frequencies then add it as a variable in an array?

前端 未结 3 1191
天命终不由人
天命终不由人 2021-01-12 18:33

Let\'s say I have an array of this format

X  Y  Z
A  1  0
A  2  1
B  1  1
B  2  1
B  1  0

I want to find the frequency of X and the frequen

3条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-12 18:55

    Using ave and assuming your data is dat

    dat$Fx <-  with(dat,ave(Y,list(X),FUN=length))
    dat$Fyx <- with(dat,ave(Y,list(X,Y),FUN=length))
    

    Result:

      X Y Z Fx Fyx
    1 A 1 0  2   1
    2 A 2 1  2   1
    3 B 1 1  3   2
    4 B 2 1  3   1
    5 B 1 0  3   2
    

    If the data doesn't have a numeric column for ave to work on, then:

    dat$Fx <-  with(dat,ave(seq_len(nrow(dat)),list(X),FUN=length))
    dat$Fyx <- with(dat,ave(seq_len(nrow(dat)),list(X,Y),FUN=length))
    

提交回复
热议问题