r - Getting column names of each row in order -
i have dataframe 3 columns of numeric values. want sort each row , print string column names in sorted order each row. here code:
> df <- data.frame(x = c(1,2,3), y = c(3,1,2), d = c(4,0, 5)) > df x y d 1 1 3 4 2 2 1 0 3 3 2 5 > for(r in 1:nrow(df)) + print(paste(colnames(sort(df[r,])), collapse = " ")) [1] "x y d" [1] "d y x" [1] "y x d"
this work, takes long time when have large dataframe. there more effective way perform sort? tried use apply, gave blank strings:
> apply(df, 1, function(row) paste( colnames( sort( row, decreasing = t )) , collapse = " " )) [1] "" "" ""
when call function within apply on single row, works:
> paste( colnames( sort( df[1,], decreasing = t )) , sep = " " ) [1] "d" "y" "x"
i looking faster way perform operation on each row of large dataframe loop. , think apply faster, cannot work.
t(apply(df, 1, function(x) names(x)[order(x)]))
this question popped again in reading, thought shall edit add more ways of doing it.. might later :
library(data.table) setdt(df)[, paste(colnames(df)[order(.sd)], collapse = " "), = 1:nrow(df)]
logic : groupby row index( means row-wise operation) - apply rank
each group(which row). .sd
means subset of data( columns)( can control using .sdcols =
argument. simple paste
column names accordingly
same logic above implemented in dplyr
library(dplyr) library(tidyr) df %>% rowwise() %>% do(rank = paste(colnames(df)[order(unlist(.))], collapse = " ")) %>% unnest()
output :
# nrow v1 #1: 1 x y d #2: 2 d y x #3: 3 y x d
Comments
Post a Comment