根据字符串条件创建子集

时间:2018-02-12 09:04:34

标签: r

Havig这样的数据框:

df_in <- data.frame(x = c('x1','x2','x3','x4'),
                     col1 = c('http://youtube.com/something','NA','https://www.yahooexample.com','https://www.yahooexample2.com'),
                     col2 = c('https://google.com', 'http://www.bbcnews2.com?id=321','NA','https://google.com/text'),
                     col3 = c('http://www.bbcnews.com?id=321', 'http://google.com?id=1234','NA','https://bbcnews.com/search'),
                     col4 = c('NA', 'https://www.youtube/com','NA', 'www.youtube.com/searcht'))

在控制台中打印的数据框输入示例:

 x                          col1                           col2                          col3                    col4
1 x1  http://youtube.com/something             https://google.com http://www.bbcnews.com?id=321                      NA
2 x2                            NA http://www.bbcnews2.com?id=321     http://google.com?id=1234 https://www.youtube/com
3 x3  https://www.yahooexample.com                             NA                            NA                      NA
4 x4 https://www.yahooexample2.com        https://google.com/text    https://bbcnews.com/search www.youtube.com/searcht

我想创建特定子集条件的数据框。示例我想只保留包含&#34; google&#34;,&#34; youtube&#34;和&#34; bbc&#34;他们的刺痛。 预期产出的例子:

df_out <- data.frame(x = c('x1','x2','x4'),
                     col1new = c('http://youtube.com/something', 'http://www.bbcnews2.com?id=321', 'https://google.com/text'),
                     col2new = c('https://google.com', 'http://google.com?id=1234', 'https://bbcnews.com/search'),
                     col3new = c('http://www.bbcnews.com?id=321', 'https://www.youtube/com', 'www.youtube.com/searcht'))

在控制台中打印的数据框输出示例:

 x                        col1new                    col2new                       col3new
1 x1   http://youtube.com/something         https://google.com http://www.bbcnews.com?id=321
2 x2 http://www.bbcnews2.com?id=321  http://google.com?id=1234       https://www.youtube/com
3 x4        https://google.com/text https://bbcnews.com/search       www.youtube.com/searcht

1 个答案:

答案 0 :(得分:2)

我们可以使用grep创建一个逻辑条件,根据http://

之后具有至少一个模式的元素条目来过滤行
i1 <- Reduce('|', lapply(df_in[-1], grepl, pattern= "https?://(google|youtube|bbc)"))

然后,循环遍历子集数据的行并获取与google/youtube/bbc

匹配的链接
tmp <- t(apply(df_in[i1,-1], 1, function(x) x[grepl("(google|youtube|bbc)", x)]))
colnames(tmp) <- paste0('col', seq_len(ncol(tmp)), "new")

cbind包含第一列的子集

cbind(df_in[i1, 1, drop = FALSE], tmp)
#   x                        col1new                    col2new                       col3new
#1 x1   http://youtube.com/something         https://google.com http://www.bbcnews.com?id=321
#2 x2 http://www.bbcnews2.com?id=321  http://google.com?id=1234       https://www.youtube/com
#4 x4        https://google.com/text https://bbcnews.com/search       www.youtube.com/searcht