简体   繁体   中英

How would I change TRUE values in a cell to the name of a column header (R programming)

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"?

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.

try with this:

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

where 2 is the column index

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM