-1

Mars:

ticket  Name    Fare
  A3    Emily    50
  A4    Jack     50
  A5    Sam      25
  A6    Lara     25
  A4    Julie    50
  A3    Kevin    50

When we go to the movies, sometimes we buy one ticket for two people's price. Now I need to count the repeated data. I know how to count it, but not sure how to put it back into the data frame since the length will be different.

My code:

a <- as.data.frame(table(Mars$ticket))
Mars$Count <- Mars$ticket[a$Var2]

Output:

var1   Var2
A3      2
A4      2
A5      1
A6      1

Error
  replacement has 4 rows, data has 6

Expected output:

Mars:

ticket  Name    Fare  Count
  A3    Emily    50     2
  A4    Jack     50     2
  A5    Sam      25     1
  A6    Lara     25     1
  A4    Julie    50     2
  A3    Kevin    50     2
Makiyo
  • 441
  • 5
  • 23

2 Answers2

2

You can use merge like this

df <- read.table(text = "ticket  Name    Fare
A3    Emily    50
A4    Jack     50
A5    Sam      25
A6    Lara     25
A4    Julie    50
A3    Kevin    50", header = T)

a <- as.data.frame(table(df$ticket))

merge(df, a, by.x = "ticket", by.y = "Var1", all.x = T)

  ticket  Name Fare Freq
1     A3 Emily   50    2
2     A3 Kevin   50    2
3     A4  Jack   50    2
4     A4 Julie   50    2
5     A5   Sam   25    1
6     A6  Lara   25    1
Hardik Gupta
  • 4,700
  • 9
  • 41
  • 83
1

Assuming that 'ticket' is character class, we use the 'ticket' to match the names of 'table' and expand the values

Mars$Count <- with(Mars, as.vector(table(ticket)[ticket]))
Mars$Count
#[1] 2 2 1 1 2 2
akrun
  • 874,273
  • 37
  • 540
  • 662