Samuel
Samuel

Reputation: 165

Counting character values in R

I have a dataframe which looks like below.

data <- data.frame(Var_1 = c("A","B","C","A","B"))

Var_1
A
B
C
A
B

Need to do count like below.

Var_1 Count
A     2
B     2
C     1
A     2
B     2

Upvotes: 0

Views: 8329

Answers (2)

Ishan
Ishan

Reputation: 21

I believe you can try using the table and storing it as a dataframe, from this data frame you can access the frequency of your data.

    > data <- data.frame(Var_1 = c("A","B","C","A","B"))
    > df <- as.data.frame(table(data))
    > df$data
    [1] A B C
    Levels: A B C
    > df$Freq
    [1] 2 2 1
    > df
      data Freq
    1    A    2
    2    B    2
    3    C    1

PS: I am not sure if you mean to repeat the 'levels' of your data as mentioned in your question, but unless it is case specific (which is not mentioned) I would take a repetitive class or level into consideration.

Upvotes: 2

din
din

Reputation: 692

# sample data
df <- data.frame(Var_1 = c("A","B","C","A","B"))

# make a frequency table to determine the "count"
countsDF <- table(df$Var_1)

# use names to match the Var_1 in the countsDF, then assign
# the corresponding count
df$count <- countsDF[match(df$Var_1,  names(countsDF))]

Upvotes: 3

Related Questions