Yue Zhang
Yue Zhang

Reputation: 13

Extract and calculate frequency of occurrence in column using R

I have a .csv file, which is like

  COLUMN1  COLUMN2 COLUMN3 COLUMN4
1       a 12/16/17       1       1
2       b       15       1       2
3       c       18       1       3
4       d    12/15       4       5
5       e    13/12       1       5

How to count the times of a number x appears in COLUMN2? The result I expect is

12 15 13 16 17 18 
 3  2  1  1  1  1

Upvotes: 0

Views: 436

Answers (2)

akrun
akrun

Reputation: 886938

We can use scan with table

table(scan(text=df1$COLUMN2, sep="/", what=numeric(), quiet = TRUE))
# 12 13 15 16 17 18 
# 3  1  2  1  1  1 

If the column is factor, convert to character and use it in scan

table(scan(text=as.character(df1$COLUMN2), sep="/", 
                              what=numeric(), quiet = TRUE))

Upvotes: 2

Zheyuan Li
Zheyuan Li

Reputation: 73265

We can use strsplit and table:

x <- c("12/16/17", "15", "18", "12/15", "13/12")
# [1] "12/16/17" "15"       "18"       "12/15"    "13/12" 

y <- unlist(strsplit(x, split="/"))
# [1] "12" "16" "17" "15" "18" "12" "15" "13" "12"

z <- table(y)
#12 13 15 16 17 18 
# 3  1  2  1  1  1 

If you want exactly the order as in your question, you need to code y into factor with desired levels:

z <- table(factor(y, levels = unique(y)))
#12 16 17 15 18 13 
# 3  1  1  2  1  1 

Upvotes: 2

Related Questions