获取R数据帧中包含特定字符的每行的列号

获取R数据帧中包含特定字符的每行的列号,r,dataframe,R,Dataframe,如果我有一个像下面这样的数据框 a <- c('A', 'b', 'c') b <- c('b', 'c', 'A') c <- c('c', 'A', 'b') df <- data.frame(a, b, c) df a b c 1 A b c 2 b c A 3 c A b a单向使用ifelse和grep df$b_pos <- ifelse(apply(df, 1, function(i) grep('A', i)) >

如果我有一个像下面这样的数据框

a <- c('A', 'b', 'c')
b <- c('b', 'c', 'A')
c <- c('c', 'A', 'b')
df <- data.frame(a, b, c)

df
  a b c
1 A b c
2 b c A
3 c A b

a单向使用
ifelse
grep

df$b_pos <- ifelse(apply(df, 1, function(i) grep('A', i)) > 
                          apply(df, 1, function(i) grep('b', i)), 'before A', 'after A')

df$c_pos <- ifelse(apply(df[,1:3], 1, function(i) grep('A', i)) > 
                     apply(df[,1:3], 1, function(i) grep('c', i)), 'before A', 'after A')
df
#  a b c    b_pos    c_pos
#1 A b c  after A  after A
#2 b c A before A before A
#3 c A b  after A before A
df$b_位置
应用(df,1,函数(i)grep('b',i)),'在A之前','在A之后')
df$c_pos
应用(df[,1:3],1,函数(i)grep('c',i)),'before A','after A')
df
#a b c b_位置c_位置
#一个接一个,一个接一个
#2 b c A在A之前在A之前
#3在A之后在A之前
如果您可以保证“A”在每行中恰好出现一次,那么您可以得到如下列索引向量:

> apply(df=="A",1,which)
[1] 1 3 2

我们可以使用
max.col

df[c('b_pos', 'c_pos')] <- lapply(letters[2:3], function(x) 
         c("before A", "after A")[1+(max.col(df=="A", "first") < max.col(df==x, "first"))])
df
#  a b c    b_pos    c_pos
#1 A b c  after A  after A
#2 b c A before A before A
#3 c A b  after A before A
> apply(df=="A",1,which)
[1] 1 3 2
df[c('b_pos', 'c_pos')] <- lapply(letters[2:3], function(x) 
         c("before A", "after A")[1+(max.col(df=="A", "first") < max.col(df==x, "first"))])
df
#  a b c    b_pos    c_pos
#1 A b c  after A  after A
#2 b c A before A before A
#3 c A b  after A before A
df[c('b_pos', 'c_pos')] <- lapply(c("A.*b",  "A.*c"), function(x) 
           c("before A", "after A")[grepl(x, do.call(paste0, df))+1L])