Home > Back-end >  Subset R dataframe by column values and change cells that match certain value to new value
Subset R dataframe by column values and change cells that match certain value to new value

Time:11-16

I have a one-row dataframe that I need to append onto an existing table. As it is, many of the dataframe values are booleans, but I need to convert them to strings ('-1' for TRUE, '0' for FALSE) to match the existing table. Since the dataframe contains 100s of such columns, I would like to avoid typing each individual column. I've tried to use which(TRUE) and isTRUE(), but if those would work in my case, I'm not sure what to use as the function arguments, or how to put them into a dataframe.

I think it would be something like this:

df <- data.frame(a = T, b = F, c = F, d = T, e = T, f = T, g = F, h = F)
df2 <- df[, {find all values that are true}]${all those columns} <- '-1'
df3 <- df2[, {find all values that are false}]${all those columns} <- '0'

## df3 should match this:
df3 <- data.frame(a = '-1', b = '0', c = '0', d = '-1', e = '-1', f = '0', g = '0', h = '0')

I searched pretty thoroughly in the dplyr documentation, as well as on this site and googling and found a lot of similar questions, but nothing that quite matched my situation. Thanks!

CodePudding user response:

Have you tried using across() logical columns ? Below is an example where I added a column with a numeric value and used a function to mutate only logical columns with across().

df <- data.frame(a = T, b = F, c = F, d = T, e = T, f = T, g = F, h = F, non.logical.column = 1)

conv.logical <- function(x){
  if(isTRUE(x)){-1}else{0}
}

df <- df %>% mutate(across(where(is_logical), conv.logical))
  • Related