-1

I have no idea where to start with this, but what I am trying to do is create a new value based on the number of times another value is represented in another column.

For example

# Existing Data
key newcol
a   ?
a   ?
a   ?
b   ?
b   ?
c   ?
c   ?
c   ?

Would like the output to look like

key newcol
a   3
a   3
a   3
b   2
b   2
c   3
c   3
c   3

Thanks!

Starbucks
  • 1,448
  • 3
  • 21
  • 49
  • You should read some introductory material and show what you tried. Everything you need to know for this is in the [Introduction to `dplyr` vignette](https://cran.r-project.org/web/packages/dplyr/vignettes/dplyr.html). If you try a couple things and they don't work, we can help you work through the problems. – Gregor Thomas Mar 08 '18 at 20:21
  • 1
    Question title has nothing to do what you're asking – pogibas Mar 08 '18 at 20:27

2 Answers2

1

This can be achieved with the doBy package like so:

require(doBy)

#original data frame
df <- data.frame(key = c('a', 'a', 'a', 'b', 'b', 'c', 'c', 'c'))

#add counter 
df$count <- 1

#use summaryBy to count number of instances of key
counts <- summaryBy(count ~ key, data = df, FUN = sum, var.names = 'newcol', keep.names = TRUE)

#merge counts into original data frame
df <- merge(df, counts, by = 'key', all.x = TRUE)

df then looks like:

> df
  key count newcol
1   a     1      3
2   a     1      3
3   a     1      3
4   b     1      2
5   b     1      2
6   c     1      3
7   c     1      3
8   c     1      3
93i7hdjb
  • 1,136
  • 1
  • 9
  • 15
-1

If key is a vector like this key <- rep(c("a", "b", "c"), c(3,2,3)), then you can get what you want by using table to count occurences of key elements

> N <- table(key)
> data.frame(key, newcol=rep(N,N))
  key newcol
1   a      3
2   a      3
3   a      3
4   b      2
5   b      2
6   c      3
7   c      3
8   c      3

On the other hand, if key is a data.frame, then...

key.df <- data.frame(key = rep(letters[1:3], c(3, 2, 3)))
N <- table(key.df$key)
data.frame(key=key.df, newcol=rep(N, N))   
Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138