0

I have a data frame with one column. There are 10 rows.

(4.0 * 3.0)
(4.0 * 3.0)
(2.0 * (1.0 * (1.0 * 6.0)))
(4.0 * (3.0 * 1.0))
(6.0 * 2.0)
(6.0 * 2.0)
(2.0 * 6.0)
(2.0 * 6.0)
(2.0 * 6.0)
(6.0 * 2.0)

I need to extract the unique values in the column and the number of times it occurs. Using sqldf package I was able to get the unique values. But not the count.

Query:

sqldf("SELECT V1, COUNT(DISTINCT V1) as DinctC from dataset GROUP BY V1")

Output:

                           V1 DinctC
1 (2.0 * (1.0 * (1.0 * 6.0)))      1
2                 (2.0 * 6.0)      1
3         (4.0 * (3.0 * 1.0))      1
4                 (4.0 * 3.0)      1
5                 (6.0 * 2.0)      1

What I want is:

                           V1 DinctC
1 (2.0 * (1.0 * (1.0 * 6.0)))      1
2                 (2.0 * 6.0)      3
3         (4.0 * (3.0 * 1.0))      1
4                 (4.0 * 3.0)      2
5                 (6.0 * 2.0)      3

Edit: As Tim Biegeleisen pointed out "Distinct" is not a function therefore no need of the brackets. So updating DISTINCT(V1) to DISTINCT V1

2 Answers 2

5

We do not need the distinct keyword as we are using the GROUP BY clause.

sqldf("SELECT V1, COUNT(V1) as DinctC from dataset GROUP BY V1")

Result:

                           V1 DinctC
1 (2.0 * (1.0 * (1.0 * 6.0)))      1
2                 (2.0 * 6.0)      3
3         (4.0 * (3.0 * 1.0))      1
4                 (4.0 * 3.0)      2
5                 (6.0 * 2.0)      3
Sign up to request clarification or add additional context in comments.

Comments

1

We can use count

library(dplyr)
count(df, V1)
# A tibble: 5 x 2
#                          V1     n
#                       <chr> <int>
#1 (2.0 * (1.0 * (1.0 * 6.0)))     1
#2                 (2.0 * 6.0)     3
#3         (4.0 * (3.0 * 1.0))     1
#4                 (4.0 * 3.0)     2
#5                 (6.0 * 2.0)     3

Or table from base R

table(df$V1)

2 Comments

Thank you very much. However I'm looking for a way to get the same result with sqldf. In case I didn't find I'm going to use this method.
@SriniShine Thanks for the comments. I guess you already got another solution with sqldf

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.