Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

links between data in R

Tags:

dataframe

r

I have a data.frame of this form:

        C1    C2   C3 support
1      {A}   {B} <NA>    1.00
2      {D}   {A} <NA>    0.50
3      {F}   {A} <NA>    0.30
4      {D}   {F}  {A}    0.75
5    {B,F}   {A} <NA>    0.50
6      {D} {B,F}  {A}    0.25

and I want to transform above data.frame to following:

      FROM    TO      support
1      {A}   {B}         1.00
2      {D}   {A}         0.50
3      {F}   {A}         0.30
4      {D}   {F}         0.75
5      {F}   {A}         0.75
6    {B,F}   {A}         0.50
7      {D} {B,F}         0.25
8    {B,F}   {A}         0.25

This is every link between (`C1` and `C2`) and (`C2` and `C3`).
Thank you in advance.

like image 887
tshan Avatar asked Apr 25 '26 21:04

tshan


1 Answers

One option would be to rbind the subset of dataset with columns from 2nd to 4th (based on the non-NA values in the third column) to the full dataset without the 3rd column, place it in a list and use rbindlist (from data.table) to row bind the elements of the list. If needed, we can change the column names with setnames.

library(data.table)
setnames(rbindlist(list(df[, c(1,2,4)], df[!is.na(df[,3]), 2:4])),
              1:2, c("FROM", "TO"))[]
#    FROM    TO support
#1:   {A}   {B}    1.00
#2:   {D}   {A}    0.50
#3:   {F}   {A}    0.30
#4:   {D}   {F}    0.75
#5: {B,F}   {A}    0.50
#6:   {D} {B,F}    0.25
#7:   {F}   {A}    0.75
#8: {B,F}   {A}    0.25

data

df <- structure(list(`1` = c("{A}", "{D}", "{F}", "{D}", "{B,F}", "{D}"
), `2` = c("{B}", "{A}", "{A}", "{F}", "{A}", "{B,F}"), `3` = c(NA, 
NA, NA, "{A}", NA, "{A}"), support = c(1, 0.5, 0.3, 0.75, 0.5, 
 0.25)), .Names = c("1", "2", "3", "support"), class = "data.frame", 
row.names = c(NA, -6L))
like image 105
akrun Avatar answered Apr 27 '26 15:04

akrun



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!