0

Assume I have a table that has TRUE and FALSE values, and I need to change the values of TRUE values to the name of column headers, and the false values to an empty space. Changing false values is easy since every cell value that is FALSE will always get changed to an empty space, so I can do this

dataset[dataset == "FALSE'] <- " "

Assume that I have row 81 under COL2, and it is TRUE, how would I change "TRUE" to "COL2"?

Heroka
  • 12,889
  • 1
  • 28
  • 38
Mark
  • 65
  • 3
  • 1
    Please consider reading up on [ask] and how to produce a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). Makes it easier for others to help you. – Heroka Jan 11 '16 at 09:29

2 Answers2

4

With this starting dataset:

df <- structure(list(C1 = c(TRUE, FALSE, FALSE), c2 = c(FALSE, FALSE,TRUE), C3 = c(FALSE, FALSE, FALSE)), .Names = c("C1", "c2", "C3"), row.names = c(NA, -3L), class = "data.frame")

I would use:

df[df==TRUE] <- colnames(df)[which(df==TRUE, arr.ind=TRUE)[,'col']]

which gives:

> df
     C1    c2    C3
1    C1 FALSE FALSE
2 FALSE FALSE FALSE
3 FALSE    c2 FALSE

which with arr.ind give where there's a true value in row column format, getting only the columns gives us the indexes to select the colnames, and then replace the true values by this result.

Your line of code for the false cases being already ok, I did not report it here.

Jaap
  • 81,064
  • 34
  • 182
  • 193
Tensibai
  • 15,557
  • 1
  • 37
  • 57
-1

try with this:

dataset[dataset == "FALSE"] <- colnames(dataset)[2]

where 2 is the column index

ntrax
  • 457
  • 4
  • 22