MCmr
MCmr

Reputation: 11

Calling different variables depending on the values of one other variable

I have a column A, which values are characters a, b, c ; and then i have three other columns also called a, b and c; I would like to create a column Z that is equal to the value of a when A == 'a', to the value of b when A == 'b', and c when A =='c'; I have :

**A | a    | b   | c** 
  a | 1    | 0,7 | 3,4
  a | 1,1  | 0,8 | 3,5
  c | 1,15 | 0,9 | 3,4
  b | 1,1  | 0,7 | 3,4

and i want to create Z like this:

**A | a    | b   | c  | Z**
  a | 1    | 0,7 | 3,4| 1
  a | 1,1  | 0,8 | 3,5| 1,1
  c | 1,15 | 0,9 | 3,4| 3,4
  b | 1,1  | 0,7 | 3,4| 0,7

This is a simple example but actually A has more than 30 modalities, i can do it easily with many ifelse, but i'd need to do it in a neat way since i have a huge amount of obs

Upvotes: 1

Views: 50

Answers (2)

Diego Rodrigues
Diego Rodrigues

Reputation: 864

You can use the apply function to do it:

df <- data.frame("A" = c("a","a","b","c"),
                 "a" = seq(1,4),
                 "b" = seq(5,8),
                 "c" = seq(9,12)
                 ,stringsAsFactors = F)

df$Z <- apply(df,1,function(x){
          return(x[x["A"]])
        })

  A a b  c  Z
1 a 1 5  9  1
2 a 2 6 10  2
3 b 3 7 11  7
4 c 4 8 12 12

Upvotes: 0

zx8754
zx8754

Reputation: 56219

Using sapply and match:

#data
df1 <- read.table(text = "A|a|b|c
a|1|0,7|3,4
a|1,1|0,8|3,5
c|1,15|0,9|3,4
b|1,1|0,7|3,4", header = TRUE, sep = "|")

# add matching column to Z
df1$Z <- sapply(1:nrow(df1), function(i)
  df1[i, match(df1[i, "A"], colnames(df1))])

df1
#   A    a   b   c   Z
# 1 a    1 0,7 3,4   1
# 2 a  1,1 0,8 3,5 1,1
# 3 c 1,15 0,9 3,4 3,4
# 4 b  1,1 0,7 3,4 0,7

Upvotes: 2

Related Questions