1

for example, this is my data

mydata
  v
1 1
2 1
3 2
4 2
5 2
6 3

is there any function that can generate a vector or column like

  v counts
1 1      2
2 1      2
3 2      3
4 2      3
5 2      3
6 3      1

I tried the method of sum(),but failed

mydata$counts <- sum(mydata$v == mydata$v)
David Arenburg
  • 91,361
  • 17
  • 137
  • 196
Shanqiao Chen
  • 91
  • 1
  • 8
  • 4
    `ave` might help here, like `ave(x,x,FUN=length)` – Frank Jun 17 '15 at 14:35
  • For future reference, the correct r tag is [tag:data.frame] and there's no need to embed r code in html snippet blocks, since html and r are unrelated. (These problems have been fixed on your post already.) – Frank Jun 17 '15 at 14:39
  • 5
    Also `library(data.table) ; setDT(mydata)[, counts := .N, by = v]` – David Arenburg Jun 17 '15 at 14:44

5 Answers5

4

Another base R option with ave:

within(mydata, counts <- ave(v, v, FUN=length))
Matthew Plourde
  • 43,932
  • 7
  • 96
  • 113
2
library(dplyr)
mutate(group_by(mydata,v),count=(length(v)))
Shenglin Chen
  • 4,504
  • 11
  • 11
  • 3
    A more correct syntax would be probably `mydata %>% group_by(v) %>% mutate(counts = n())` or maybe `mydata %>% left_join(count(., v))` but whatever. – David Arenburg Jun 17 '15 at 14:53
1

Using base R:

mydata$counts <- with(mydata, table(v)[as.character(v)])
Nick Kennedy
  • 12,510
  • 2
  • 30
  • 52
1

Using ddply

library(plyr)
ddply(mydata, .(v), mutate, counts = length(v))

#  v counts
#1 1      2
#2 1      2
#3 2      3
#4 2      3
#5 2      3
#6 3      1

Or lapply

do.call(rbind, lapply(split(mydata, mydata$v), 
        function(x){ x$counts = length(x$v); x}))

#    v counts
#1.1 1      2
#1.2 1      2
#2.3 2      3
#2.4 2      3
#2.5 2      3
#3   3      1
Veerendra Gadekar
  • 4,452
  • 19
  • 24
-3
> mydata
  v
1 1
2 1
3 2
4 2
5 2
6 3

I would use something like this:

as.data.frame(table(a))

a Freq 1 1 2 2 2 3 3 3 1

gh0strider18
  • 1,140
  • 3
  • 13
  • 23