R将文件名附加到列的值

R将文件名附加到列的值,r,dplyr,igraph,R,Dplyr,Igraph,我有很多列的数据要转换为igraph对象。一些值存在于多个列中,因此我想添加列的名称来标识这些值。下面是一个可复制的示例 # sample of original data head(as.data.frame(Titanic)) # sample of the data after the col name has been appended to the value of the column data.frame(Class = c("Class_1st","Class_2nd"

我有很多列的数据要转换为igraph对象。一些值存在于多个列中,因此我想添加列的名称来标识这些值。下面是一个可复制的示例

# sample of original data
head(as.data.frame(Titanic))

 # sample of the data after the col name has been appended to the value of the column 

 data.frame(Class = c("Class_1st","Class_2nd","Class_3rd","Class_Crew","Class_1st","Class_2nd"),
        Sex = c("Sex_Male","Sex_Male","Sex_Male","Sex_Male","Sex_Female","Sex_Female"),
       Age =  c("Age_Child","Age_Child","Age_Child","Age_Child","Age_Child","Age_Child"),
       Survived =   c("Survived_No","Survived_No","Survived_No","Survived_No","Survived_No","Survived_No"), 
Freq = c(0,0,35,0,0,0), stringsAsFactors = FALSE)

不确定这是否是您想要的,但它与您的示例输出相匹配

df <- head(as.data.frame(Titanic))
df[,1:4] <- paste(names(df[,1:4])[col(df[,1:4])], unlist(df[,1:4]), sep="_")

df这一点尚不清楚。有些值存在于多个列中是什么意思?文件名来自何处,它们与数据的关系如何?我还将删除
igraph
标记,因为这个问题本身可能不依赖于
igraph
,即使这是您更大的目标。相同的值,例如“Y”或“N”存在于多个列中,因此我需要附加列的名称来跟踪这些值。好的,您需要发布一个正在处理的数据样本,这不仅仅是成功完成的数据样本。目前还不清楚文件名的来源。写一篇容易回答的R文章