Yue Zhang Yue Zhang - 3 months ago 9
R Question

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

Answer

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))