Ben K.
Ben K.

Reputation: 33

assign frequency as new column in r

Let's say I have the following string:

a <- c("a", "b", "c", "b", "a", "a", "e")
b <- table(a)

b gives me the frequency of every element in a. How do I create a dataframe with two columns, the first column is a and in the second I have the frequency of each element?

The output should look like this:

f <- c(3, 2, 1, 2, 3, 3, 1)
output <- data.frame(a,f)

Thank you very much in advance!

Upvotes: 1

Views: 444

Answers (2)

Edward
Edward

Reputation: 18683

Using merge:

merge(as.data.frame(a), as.data.frame(table(a)))

#  a Freq
#1 a    3
#2 a    3
#3 a    3
#4 b    2
#5 b    2
#6 c    1
#7 e    1

Upvotes: 2

akrun
akrun

Reputation: 887118

We can use add_count to create a new column

library(tibble)
library(dplyr)
tibble(a) %>% 
     add_count(a)

Or in base R with ave

data.frame(a, freq = ave(seq_along(a), a, FUN = length))

Or if it needs to be from 'b', do the match with the names of 'b' and the vector 'a' to expand the table output and then convert the table object to data.frame with as.data.frame

as.data.frame(b[a])
#  a Freq
#1 a    3
#2 b    2
#3 c    1
#4 b    2
#5 a    3
#6 a    3
#7 e    1

Upvotes: 3

Related Questions