P.Hubert
P.Hubert

Reputation: 147

Compare variable names with String to compute new variable

I want to use variable names in R for comparison with String-Data in an id-Variable.

Table 1 shows how my sample table is currently looking and Table 2 shows what I want to achieve. In Table 2 corresponding values are copied into a new variable "newid" if the variable id matches the column name. The other values are also copied into new variables for easier calculating

id    a    b    c   newid

c     1    2    3   
a     4    2    1   
b     5    8    9   

id    a    b    c   newid   rest1   rest2

c     1    2    3   3       1       2
a     4    2    1   4       2       1
b     5    8    9   8       5       9

Thank you in advance

Upvotes: 2

Views: 185

Answers (3)

BENY
BENY

Reputation: 323226

By using melt from reshape

temp=with(melt(dt,'id'),melt(dt,'id')[id==variable,])
dt$New=temp$value[match(dt$id,temp$variable)]
dt
  id a b c New
1  c 1 2 3   3
2  a 4 2 1   4
3  b 5 8 9   8

Upvotes: 0

Roland
Roland

Reputation: 132706

Using match and subsetting with an index matrix:

DF <- read.table(text = "id    a    b    c
c     1    2    3   
a     4    2    1   
b     5    8    9 ", header = TRUE)

DF$newid <- DF[, -1][cbind(seq_len(nrow(DF)), 
                           match(DF$id, colnames(DF)[-1]))]
#  id a b c newid
#1  c 1 2 3     3
#2  a 4 2 1     4
#3  b 5 8 9     8

Upvotes: 2

Sotos
Sotos

Reputation: 51582

An approach via tidyverse,

library(tidyverse)

df %>% 
 gather(var, val, -id) %>% 
 filter(id == var) %>% 
 left_join(df, ., by = 'id') %>% 
 select(-var)

which gives,

  id a b c val
1  c 1 2 3   3
2  a 4 2 1   4
3  b 5 8 9   8

Upvotes: 2

Related Questions