Convert data frame of N columns into a data frame of two 'stacked' columns

前端 未结 1 1533
耶瑟儿~
耶瑟儿~ 2021-01-20 15:56

Hello Stack Community.

I am doing work with network analytics and have a data reshaping question.

My original data comes in as a series of columns each colu

相关标签:
1条回答
  • 2021-01-20 16:27

    If I understand correctly, you can just use unlist and manually create your data.frame:

    mydf[] <- lapply(mydf, as.character)  # Convert factors to characters
    final_output <- data.frame(Source = unlist(mydf[-length(mydf)]), 
                               Target = unlist(mydf[-1]))
    head(final_output, 15)
    #       Source Target
    # varA1      A      B
    # varA2      A      B
    # varA3      A      B
    # varA4      A      B
    # varA5      A      B
    # varA6      A      B
    # varB1      B      C
    # varB2      B      C
    # varB3      B      C
    # varB4      B      C
    # varB5      B      C
    # varB6      B      C
    # varC1      C      D
    # varC2      C      D
    # varC3      C      D
    
    0 讨论(0)
提交回复
热议问题