将N列数据框转换为两个“堆叠”列的数据框。

3

大家好,Stack社区。

我正在进行网络分析的工作,有一个数据重塑的问题。

我的原始数据由一系列列组成,每列都是一个“源”和“目标”对。最终的数据框需要由两列“源”和“目标”组成。请注意,这些对是交错的,因为源和目标是如同有向网络一样相互连接的。(请参见代码示例中的final_output以获取期望的输出)

我创建了一个非常不专业的方法来产生我需要的输出(请参见下面的代码),但它没有考虑到不同数量的列,除非我添加变量等等。此外,请注意,在某些情况下,列对的数量将是奇数,即数据框末尾会有一个“源”而没有“目标”。在这种情况下,缺少的“目标”列将被创建为NAs。

我感觉有一种更顺畅的方法可以实现这一点,而不需要手工操作。我一直在搜索,但没有找到任何东西。非常感谢您的帮助。

蒂姆

# Create example DF
mydf <- data.frame(id = 1:6, varA = "A",
               varB = "B",
               varC = "C",
               varD = "D",
               varE = "E",
               varF = "F")
#Remove the ID value for DF build. This variable is not in real DF
mydf$id <-NULL

#Begin inelegant hack. 
#Please note: the incoming DF has an indeterminate number of columns that vary with project

counter <-ncol(mydf)
   for (i in 1:counter){
   t1 <-mydf[(counter-counter+1):(counter-counter+2)] 
   t2 <-mydf[(counter-counter+2):(counter-counter+3)]
   t3 <-mydf[(counter-counter+3):(counter-counter+4)]
   t4 <-mydf[(counter-counter+4):(counter-counter+5)]
   t5 <-mydf[(counter-counter+5):(counter-counter+6)]
    }

#Rename for the rbind
names(t1) <-c("Source", "Target")
names(t2) <-c("Source", "Target")
names(t3) <-c("Source", "Target")
names(t4) <-c("Source", "Target")
names(t5) <-c("Source", "Target")

#This is the shape I need but the process is super manual and does not accommodate differing numbers of columns.
final_output <-rbind(t1,t2,t3,t4,t5)
1个回答

3

如果我理解正确,您可以直接使用unlist并手动创建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

哇塞,这个东西真是太棒了!多么简单而美妙的解决方案啊。非常感谢! - Tim Rich

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接