简体   繁体   中英

Conditionally change values in a data frame to their column name

I have a data frame that looks like this

set.seed(123)
test_data <- data.frame(id   = 1:6,
                        var1 = rbinom(n = 6, size = 1, prob = .5),
                        var2 = rbinom(n = 6, size = 1, prob = .5),
                        age  = sample(18:30, size = 6, replace = T))

I want to use dplyr or purrr to change the values that are equal to 1 in var1 and var2 , to the name of their column and keep the 0's the way they are.

The result would look like this.

id    var1  var2    age
1     0     var2    26
2     var1  var2    25
3     0     var2    19
4     var1  0       29
5     var1  var2    21
6     0     0       18

I have tried using dplyr::mutate_at

mutate_at(test_data,
          vars(var1, var2), 
          function(var_x) { ifelse(var_x == 1, colnames(var_x), var_x) })

This returns the following error. So, probably not the best way to go.

Error in evalq(sys.calls(), ) : replacement has length zero In addition: Warning message: In rep(yes, length.out = length(ans)) : 'x' is NULL so the result will be NULL

And I have tried using purrr:map_at

map_at(test_data, 
       c("var1", "var2"), 
       function(var_x) { ifelse(var_x == 1, colnames(var_x), var_x) })

And this returns this error.

Error in ans[test & ok] <- rep(yes, length.out = length(ans))[test & ok] : replacement has length zero In addition: Warning message: In rep(yes, length.out = length(ans)) : 'x' is NULL so the result will be NULL

While I'd prefer to work with dplyr or purrr , I'm open to suggestions using other approaches.

Here is an idea via tidyverse . The trick here is to gather first, replace the values and then spread

library(tidyverse)

test_data %>% 
  gather(var, val, -c(id, age)) %>% 
  mutate(val = ifelse(val == 1, var, val)) %>% 
  spread(var, val)

#  id age var1 var2
#1  1  26    0 var2
#2  2  25 var1 var2
#3  3  19    0 var2
#4  4  29 var1    0
#5  5  21 var1 var2
#6  6  18    0    0

This doesn't have to be too messy if you use an intermediate object:

ix <- which(test_data[2:3]==1,arr.ind=TRUE)
test_data[2:3][ix] <- names(test_data[2:3])[ix[,"col"]]

#  id var1 var2 age
#1  1    0 var2  26
#2  2 var1 var2  25
#3  3    0 var2  19
#4  4 var1    0  29
#5  5 var1 var2  21
#6  6    0    0  18

This should be relatively quick if you are dealing with big data as there is only one <- assignment operation to do the replacement. The overhead of making ix shouldn't be too large.

And a few base R solutions :

# Solution 1
test_data[, 2:3] <- sapply(2:3, function(x) ifelse(test_data[x]==1, names(test_data[x]), 0))

# Solution 2
test_data[, c("var1", "var2")] <- sapply(c("var1", "var2"), function(x) ifelse(test_data[x]==1, x, 0))

# Solution 3 
for (i in 2:3) {test_data[,i] <- ifelse(test_data[,i] == 1, colnames(test_data[i]), 0)}

# Solution 4 - probably the most traightforward. Most of the job is vectorised
# works also for other values than 0 and 1
for (i in 2:3) {test_data[test_data[,i]==1,i] <- colnames(test_data[i])}

# etc...

Here is an option using data.table

library(data.table)
dcast(melt(setDT(test_data), id.var = c('id', 'age'))[, 
  value := as.character(value)
       ][value == 1, value := as.character(variable)],
               id + age ~variable, value.var = "value")
#   id age var1 var2
#1:  1  26    0 var2
#2:  2  25 var1 var2
#3:  3  19    0 var2
#4:  4  29 var1    0
#5:  5  21 var1 var2
#6:  6  18    0    0

Or an option suggested by @thelatemail

cols <- c("var1","var2")
test_data[, (cols) := Map(function(x,y) replace(x,x==1,y), .SD, cols), .SDcols=cols]

Or another option is set from data.table

setDT(test_data)
for(j in seq_along(cols)){
  set(test_data, i = NULL, j = cols[j], value = as.character(test_data[[cols[j]]]))
  set(test_data, i = which(test_data[[cols[j]]] == 1), j = cols[j], value = cols[j])
}

Or we can use base R methods

d1 <- `dim<-`(names(test_data)[2:3][col(test_data[, 2:3])], dim(test_data[, 2:3]))
d1[test_data[, 2:3]==0] <- 0
test_data[, 2:3] <- d1

I would use these lines to do that, not sure, being an apprentice as I am, whether they are too clumsy:

test_data[test_data$var1==1,]$var1='var1'

test_data[test_data$var2==1,]$var2='var2'

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