OAM
OAM

Reputation: 189

R: Replace Column Name with Row Name on Bases of a Value in Data Frame

I have one data frame as follows:

df <- data.frame(halloo = c(0.04,1,1,1), ciaoo = c(1,0.05,1, 1), bird=c(1,1,1,1))
row.names(df) <- c("hallo", "ciao", "else", "some")

Here I want to check if a value in a cell ist lower/equal 0.05 and if this is the case then I´d like to change the column name by the row name of the concerning cell.

After applying a function, the final data frame should look like this:

df.final <- data.frame(hallo = c(0.04,1,1,1), ciao = c(1,0.05,1, 1), bird=c(1,1,1,1))
row.names(df.final) <- c("hallo", "ciao", "else", "some")

Actually, although I tried to find one solution I have no idea for good one. Has anyone an idea?

Thx in advance

Upvotes: 1

Views: 418

Answers (2)

mef jons
mef jons

Reputation: 302

I rely heavily on subscripting and functionals for a lot of problems, so here's an alternate in that vein:

bool <- df <= 0.05
bool <- as.data.frame(bool)
x <- pryr::compose(unlist, lapply)(
    bool,
    function(x) row.names(bool[x, TRUE][1])
    # [1] to handle duplicates - just pull row name of first match
)
names(df)[1:length(x)] <- x

Upvotes: 0

akrun
akrun

Reputation: 887971

We can use which with arr.ind=TRUE to get the row/column index matrix from the logical matrix (df <= 0.05). Subset the column vector ('i2'), remove the duplicates ('i3' - as there could be more than one row in a column that meets the condition), assign the column names of 'df' based on 'i3' to the names of 'i3'.

 i1 <- which(df <= 0.05, arr.ind=TRUE)
 i2 <-  i1[, 2]
 i3 <- i2[!duplicated(i2)]
 names(df)[i3] <- names(i3)

Upvotes: 2

Related Questions