是否有方便的方法将这两个步骤组合为一个?
df = data.frame(aa = 'A', ab = '', n = 'C')
# aa ab n
# A C
temp = df[ grep('a', names(df)) ]
# aa ab
# A
ans = temp[ temp != '' ]
# [1] "A"
预先感谢您的任何建议。
答案 0 :(得分:2)
这是一种假设您的数据框只有一行的方法-
df[grepl("a", names(df)) & df != '']
[1] "A"
感谢@thelatemail,这是针对任意行的通用解决方案-
df <- data.frame(aa = c('A','B'), ab = c('','T'), n = c('C', 'C'))
df[grepl("a", names(df)[col(df)]) & df != '']
[1] "A" "B" "T"
答案 1 :(得分:1)
library(tidyr)
library(dplyr)
df = data.frame(aa = 'A', ab = '', n = 'C')
df.long <-gather(df, col) #chaging to long format and key is col
df.long %>%
filter(col %in% grep("a",col, value = T) & value != '')