'How to create columns from anothers columns?

I want to built a dataframe like df2 from df1, looking always for the name of the column where the value is closet to 0: Where clossets_1 - closer value to 0 of the columns x,y and z. clossets_2 - closer value to 0 of the columns x and a, because x is the most received value in clossets_1. clossets_3 - closer value to 0 of the columns a and b, because a is the most received value in clossets_2.

df1

df1
#  x  y  z  a  b 
#1 1  2  3  4  3 
#2 2  3  4  1  2 
#3 3  2  4  2  1 
#4 4  3  2  3  6

Desire output:

df2 
#  x  y  z clossets_1 a clossets_2 b clossets_3
#1 1  2  3     x      4     x      3    b
#2 2  3  4     x      1     a      2    a 
#3 3  2  4     y      2     a      1    b 
#4 4  3  2     z      3     a      2    b



Solution 1:[1]

I solved it this way, using the first step of @BigFinger answer and the mlv() function from the package modeest to find the most repeated value in the closests columns

library(DescTools) 
library(modeest) 
library(tibble) 

df1 = tibble(x = c(1,2,3,4),
             y = c(2,3,2,3),
             z = c(3,4,4,2),
             clossest_1 = c("x","y","z")[apply(data.frame(x,y,z),1,function(x){which(x == Closest(x,0))})],
             a = c(4,1,2,3),
             clossest_2 = c(mlv(clossest_1),"a")[apply(data.frame(get(mlv(clossest_1)),a),1,function(x){which(x == Closest(x,0))})],
             b = c(3,2,1,2),
             clossest_3 = c(mlv(clossest_2),"b")[apply(data.frame(get(mlv(clossest_2)),b),1,function(x){which(x == Closest(x,0))})])
df1
# A tibble: 4 x 8
#      x     y     z clossest_1     a clossest_2     b clossest_3
#  <dbl> <dbl> <dbl> <chr>      <dbl> <chr>      <dbl> <chr>     
#1     1     2     3 x              4 x              3 b         
#2     2     3     4 x              1 a              2 a         
#3     3     2     4 y              2 a              1 b         
#4     4     3     2 z              3 a              2 b         

Solution 2:[2]

Here is the first step to get you started:

cols = c("x","y","z")
df2 = df1
df2$clossets_1 = cols[apply(df1[,cols], 1, function(x) {which(x == min(x))})]
df2
##   x y z a b clossets_1
## 1 1 2 3 4 3          x
## 2 2 3 4 1 2          x
## 3 3 2 4 2 1          y
## 4 4 3 2 3 6          z

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 BigFinger