0

I have a table:

ID  pheno   x1   x2   x3 
ABC 1       .43 .634 .542
BCD 0       .542 .42 .43
LOP 1       .235 .46  .78

etc

I have another table, where every ID in this table is male

ID 
ABC 
LOP
etc

I want to match those IDs in the second table and then add a column to table 1 indicating whether or not the IDs appear in table 2

Output:

ID  pheno   x1   x2   x3  sex
ABC 1       .43 .634 .542 1
BCD 0       .542 .42 .43  0
LOP 1       .235 .46  .78 1

I have tried

newtable <- table1[ifelse(table1$ID %in% table2$V1, table1$SEX <- 1, table1$SEX <-0),] 

But the sex column just outputs 0s for every line.

Your help would be much appreciated

tacrolimus
  • 500
  • 2
  • 12

1 Answers1

1

Given that you need MALE==1 and FEMALE==2, this is a solution you could use:

table1$sex <- (!table1$ID %in% table2$ID) + 1
table1

#>    ID pheno    x1    x2    x3 sex
#> 1 ABC     1 0.430 0.634 0.542   1
#> 2 BCD     0 0.542 0.420 0.430   2
#> 3 LOP     1 0.235 0.460 0.780   1

Where:

table1 <- read.table(text = "ID  pheno   x1   x2   x3 
ABC 1       .43 .634 .542
BCD 0       .542 .42 .43
LOP 1       .235 .46  .78", header = TRUE)

table2 <- data.frame(ID = c("ABC","LOP"))
Edo
  • 7,567
  • 2
  • 9
  • 19