大家好,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)