Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-order data frame to be consistent

Tags:

r

matrix

I have a data frame with 9 columns and 100,000 rows. The information in each row is mixed, like in the following example:

C1 <- c("Gender F", "Age 74", "Gender M")
C2 <- c("Age 54", "Gender M", "Col eyes Blue")
C3 <- c("Col eyes Brown","Col eyes Blue", "Age 56")
C4 <- c("Col hair Brown", "Col hair Black", "Col hair Blonde")

df <- cbind(C1, C2, C3, C4)

> df
     C1         C2              C3               C4               
[1,] "Gender F" "Age 54"        "Col eyes Brown" "Col hair Brown" 
[2,] "Age 74"   "Gender M"      "Col eyes Blue"  "Col hair Black" 
[3,] "Gender M" "Col eyes Blue" "Age 56"         "Col hair Blonde"

I would like to make this data frame consistent, in other words, I'd like to have all the "Gender" information in the same column, and so on. I am new in R and struggling to find the solution. Can anybody help?

like image 647
EleonoraP Avatar asked Jul 26 '26 15:07

EleonoraP


1 Answers

In case you have all keys in each row sort in apply will work:

 t(apply(df, 1, sort))
#     [,1]     [,2]             [,3]              [,4]      
#[1,] "Age 54" "Col eyes Brown" "Col hair Brown"  "Gender F"
#[2,] "Age 74" "Col eyes Blue"  "Col hair Black"  "Gender M"
#[3,] "Age 56" "Col eyes Blue"  "Col hair Blonde" "Gender M"

If that is not the case you can try to subset the unique keys. Where I assume the key is everything but not the last word and getting it using sub.

t1 <- sub(" [^ ]*$", "", df)
t2 <- unique(as.vector(t1))
do.call(rbind, lapply(seq_len(nrow(df)), function(i) df[i,match(t1[i,], t2)]))
#     C1         C2       C3               C4               
#[1,] "Gender F" "Age 54" "Col eyes Brown" "Col hair Brown" 
#[2,] "Gender M" "Age 74" "Col eyes Blue"  "Col hair Black" 
#[3,] "Gender M" "Age 56" "Col eyes Blue"  "Col hair Blonde"
like image 93
GKi Avatar answered Jul 28 '26 05:07

GKi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!