R:按列名称过滤数据框,并在不同的数据框列中匹配字符串
R: filter dataframe by column name with a string match in a different dataframe column
我有两个数据框如下所示。我想要做的是对第一个数据框进行子集化,以仅保留其列名出现在第二个数据框的列中的列,以及部分字符串与一个特定字符串匹配的列。实际数据更长,名称也更多样,所以我需要一些可以轻松应用于所有数据的东西。
df1:
abc1
abc2
acd1
abd1
acd2
xxx1
xxx2
1
2
3
4
5
6
7
df2:
样本
总计
abc1
5
abc2
4
所需的 df3:
abc1
abc2
xxx1
xxx2
1
2
6
7
这是我试过的
keep <- df2$sample
df3 <- df1 %>% select(contains(keep))
保留所有具有部分字符串匹配而非完整字符串匹配的列
keep <- df2$sample
df3 <- filter(df1, grepl(keep,colnames(df1)))
这给了我一个错误,输入 1 的大小必须是 1037 或 1,而不是 160
(1037= #of rows in df1, 160= #of columns)
此外,这不涉及 xxx 列。为此,我尝试了以下
cols <- colnames(df1)
keep <- list.append(keep, colnames(df1) %>% select(contains("xxx")))
keep <- list.append(keep, filter(colnames(df1), grepl("xxx",df1)))
keep <- list.append(keep, cols %>% select(contains("xxx")))
keep <- list.append(keep, filter(cols, grepl("xxx",cols)))
keep <- list.append(keep, grepl("xxx",cols))
导致错误
no applicable method for x applied to an object of class "character"
其中 x 是类似于过滤器的函数
keep <- list.append(keep, grepl("xxx",colnames(df1)))
将每个列名称的 true/false 结果附加到列表中。
我不喜欢这种做事方式,所以任何和所有解决方案都值得赞赏,列表对我来说似乎是最简单的方法。
根据 Martin Gals 的评论
df1 %>% select(contains("xxx"), df2$sample)
我有两个数据框如下所示。我想要做的是对第一个数据框进行子集化,以仅保留其列名出现在第二个数据框的列中的列,以及部分字符串与一个特定字符串匹配的列。实际数据更长,名称也更多样,所以我需要一些可以轻松应用于所有数据的东西。
df1:
abc1 | abc2 | acd1 | abd1 | acd2 | xxx1 | xxx2 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
df2:
样本 | 总计 |
---|---|
abc1 | 5 |
abc2 | 4 |
所需的 df3:
abc1 | abc2 | xxx1 | xxx2 |
---|---|---|---|
1 | 2 | 6 | 7 |
这是我试过的
keep <- df2$sample
df3 <- df1 %>% select(contains(keep))
保留所有具有部分字符串匹配而非完整字符串匹配的列
keep <- df2$sample
df3 <- filter(df1, grepl(keep,colnames(df1)))
这给了我一个错误,输入 1 的大小必须是 1037 或 1,而不是 160 (1037= #of rows in df1, 160= #of columns)
此外,这不涉及 xxx 列。为此,我尝试了以下
cols <- colnames(df1)
keep <- list.append(keep, colnames(df1) %>% select(contains("xxx")))
keep <- list.append(keep, filter(colnames(df1), grepl("xxx",df1)))
keep <- list.append(keep, cols %>% select(contains("xxx")))
keep <- list.append(keep, filter(cols, grepl("xxx",cols)))
keep <- list.append(keep, grepl("xxx",cols))
导致错误
no applicable method for x applied to an object of class "character"
其中 x 是类似于过滤器的函数
keep <- list.append(keep, grepl("xxx",colnames(df1)))
将每个列名称的 true/false 结果附加到列表中。
我不喜欢这种做事方式,所以任何和所有解决方案都值得赞赏,列表对我来说似乎是最简单的方法。
根据 Martin Gals 的评论
df1 %>% select(contains("xxx"), df2$sample)