lolo lolo -4 years ago 146
R Question

DataFrame - Unique values

Suppose I have the following data frame:

table<-data.frame(col1=c("ab ac", "ac", "ab", "ab ab", "ab","ac ac ac", "aa aa ab","aa ab ac"))

col1
1 ab ac
2 ac
3 ab
4 ab ab
5 ab
6 ac ac ac
7 aa aa ab
8 aa ab ac


And I want to create another column with unique values if there is only one value or if exists two or three similar ones or, in the other hand, the number of different values in each column.

table<-data.frame(col1=c("ab ac", "ac", "ab", "ab ab", "ab","ac ac ac", "aa aa ab","aa ab ac"),col2=c("2","ac","ab","ab","ab","ac","2","3"))

col1 col2
1 ab ac 2
2 ac ac
3 ab ab
4 ab ab ab
5 ab ab
6 ac ac ac ac
7 aa aa ab 2
8 aa ab ac 3


Can someone help me with this task.

Answer Source

Here is one idea,

sapply(strsplit(table$col1, ' '), function(i) ifelse(length(unique(i)) > 1, length(unique(i)), i))
#[1] "2"  "ac" "ab" "ab" "ab" "ac" "2"  "3" 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download