2

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

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Is there a possibility to copy the other values (so the ones that don´t fit the id) behind the “new id” Variable so that I can calculate more easily?
2

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.