I have a data like this
df<- structure(list(DES = c("AAAAA", "ABBBB", "BBDDD", "CHDDD", "NMHH",
"YNNN", "UUUU", "IMMM", "TTSGG", "MHDDD", "IIKKKKK", "UDDDD",
"AAAAA", "ABBBB"), Name = c("AB1", "TH1", "TH2", "HUA", "HUA1",
"UMA", "YIN", "YIM", "IUMH", "YIMH", "YIH", "TH2", "AB1", "TH1"
), data = c(1.399260301, 1.435057306, 1.515715678, 1.157216398,
1.452347714, 1.172466387, 1.16325675, 2.614138423, 0.895228818,
1.571925745, 1.717242238, 1.572841664, 0.924094104, 1.59458932
), Exact = c(0.000536206, 0.000910058, 0.001145037, 0.00114666,
0.001883335, 0.002365192, 0.002548559, 0.003406673, 0.004232483,
0.005164572, 0.006269242, 0.006741774, 0.009565493, 0.009581586
), Class = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L,
2L, 2L)), class = "data.frame", row.names = c(NA, -14L))
now I have another data which looks like this
df2<- structure(list(DES = c("AAAAA", "ABBBB", "BBDDD", "CHDDD"), Name = c("AB1",
"TH1", "TH2", "HUA")), class = "data.frame", row.names = c(NA,
-4L))
I am trying to get where those ones in the df2 are situated in the df1 so I do this
match(df$DES,df2$DES)
but I am interested in those with Class 1
I do this
match(df$DES,df2$DES) && df$Class ==1
I basically dont know how to subset based on class 1 , I also tried several other ways but didn't work like subset(match(df$DES,df2$DES), Class==1)
CodePudding user response:
Try this to find the indices ,
match(df[df$Class == 1 , ]$DES,df2$DES)
then
df2[na.omit(match(df[df$Class == 1 , ]$DES,df2$DES)), ]
DES Name
CodePudding user response:
Credit to r2evans--just noticed that this is the same as his comment, just wrapped in which
as akrun suggested.
df2<- data.frame(DES = c("AAAAA", "ABBBB", "BBDDD", "CHDDD"), Name = c("AB1", "TH1", "TH2", "HUA"))
which((df$DES %in% df2$DES) & (df$Class == 1L))
#> [1] 1 2 3 4
which((df$DES %in% df2$DES) & (df$Class == 2L))
#> [1] 13 14
CodePudding user response:
Another possible solution, based on dplyr::inner_join
:
library(tidyverse)
inner_join(df2, df %>% rownames_to_column) %>%
filter(Class == 1) %>% pull(rowname) %>% as.numeric
#> Joining, by = c("DES", "Name")
#> [1] 1 2 3 4
To get Class == 2
:
library(tidyverse)
inner_join(df2, df %>% rownames_to_column) %>%
filter(Class == 2) %>% pull(rowname) %>% as.numeric
#> Joining, by = c("DES", "Name")
#> [1] 13 14