gpt4 book ai didi

r - 返回单元格值与模式匹配的R数据帧的行和列位置

转载 作者:行者123 更新时间:2023-12-02 07:16:57 25 4
gpt4 key购买 nike

我有一个数据框

structure(list(Brand = c("AB", "AC", "AD", "BA", "CB", "CK"), `&TV` = c("0_640", 
"0", "1_340", "0", "0", "0"), `&TV HD` = c("1_500", "0", "0_140",
"0", "0", "0")), row.names = c(NA, 6L), class = "data.frame")

看起来像这样:
  Brand   &TV &TV HD
1 AB 0_640 1_500
2 AC 0 0
3 AD 1_340 0_140
4 BA 0 0
5 CB 0 0
6 CK 0 0

我想返回其中具有 1_模式的那些单元格的行和列值。对于上面的示例,我想返回
row col
3 2
1 3

我正在尝试使用grep,但效果不是很好。
grep(New_Brands_Theme_Combine[,c(1:length(New_Brands_Theme_Combine))], pattern = "1_")

上面给出了找到模式的数据帧的列号。如何获得列号和行号。

最佳答案

一种选择是在感兴趣的列('colnm')上循环,应用grep获取位置索引,使用列索引设置nameslist,然后将stack设置为两列data.frame

colnm <- 2:3
out <- stack(setNames(lapply(df1[colnm], grep, pattern = "1_"), colnm))
names(out) <- c("row", "col")
out
# row col
#1 3 2
#2 1 3

关于r - 返回单元格值与模式匹配的R数据帧的行和列位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60401138/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com