Reputation: 13
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
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
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