Skip to content
Prev 308834 / 398503 Next

frequency

Hi,
Assuming that there are two columns in your data.
dat1<-read.table(text="
ID??? Visit
x a1
x a2
y b1
y c23
y b33
",sep="",header=TRUE,stringsAsFactors=FALSE) 

cnt<-count(dat1$ID)
colnames(cnt)<-c("ID","response")
merge(dat1,cnt,by="ID",all=TRUE)
#? ID Visit response
#1? x??? a1??????? 2
#2? x??? a2??????? 2
#3? y??? b1??????? 3
#4? y?? c23??????? 3
#5? y?? b33??????? 3


But, if there is only column and you want to split it
ID<-c("xa1","xa2","yb1","yc23","yb33")
ID1<-gsub("(.*)a.*|b.*|c.*","\\1",ID)
?visit<-gsub(".*(a.*|b.*|c.*)","\\1",ID)
?dat2<-data.frame(ID1,visit)
dat2[]<-lapply(dat2,as.character)

?cnt<-count(dat2$ID1)
colnames(cnt)<-c("ID1","response")
?merge(dat2,cnt,by="ID1",all=TRUE)
#? ID1 visit response
#1?? x??? a1??????? 2
#2?? x??? a2??????? 2
#3?? y??? b1??????? 3
#4?? y?? c23??????? 3
#5?? y?? b33??????? 3


A.K.



----- Original Message -----
From: farnoosh sheikhi <farnoosh_81 at yahoo.com>
To: "r-help at R-project.org" <r-help at r-project.org>
Cc: 
Sent: Tuesday, October 23, 2012 3:14 PM
Subject: [R] frequency

Hello,

I have a data as follow:
ID ? ?Visit
xa1
xa2
yb1
yc23
yb33
?
I want to look at frequency of visit for ID and create a new column as response .?
For example my response would be 2 for x and 3 for y.
I think I need to write a loop, but I don't know how.
I really appreciate your help.
Thanks a lot.
Best,Farnoosh Sheikhi
??? [[alternative HTML version deleted]]


______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.