0

I have data with many columns that I want to convert to an igraph object. Some values exist in several columns so I want to add the name of the column to identify those values. Below is a reproducible example.

# 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)
user3357059
  • 1,122
  • 1
  • 15
  • 30
  • This is unclear. What do you mean by some values exist in several columns? Where do file names come from and how are they related to the data? I'd also remove the `igraph` tag, since this question itself likely won't depend on `igraph`, even though that's your larger goal. – camille Jun 27 '18 at 15:58
  • the same values e.g 'Y' or 'N' exist in several columns so I need to append the name of the column to track the values. – user3357059 Jun 27 '18 at 16:09
  • Okay, you'll need to post a sample of the data you're working with, not just a sample of data where this has been done successfully. It's still unclear where file names come in. [See this post](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) on making an R post that's easy to answer – camille Jun 27 '18 at 16:12

1 Answers1

1

Not sure if this is what you want but it matches your example output

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