2017-04-21 54 views
0

缩小我的数据帧的数量看起来是这样的:R:汇总列名称的列表映射到基于行关在一个数据帧的条件

+---+------------+-------------+ 
| | Label1 | Label2 | 
+---+------------+-------------+ 
| 1 |  T  |  F  | 
| 2 |  F  |  F  | 
| 3 |  T  |  T  | 
+---+------------+-------------+ 

我需要创建一个映射列表的列表列名称作为其所有具有假布尔值的行号。对于上面的例子会是这个样子:

{ “Label1的”:(2), “Label2的”:(1,2)}

目前我正在做它像这样:

myList = with(data.frame(which(!myDataFrame, arr.ind = TRUE)), list("colNames" = names(myDataFrame)[col], "rows" = row)) 

l = list() 
count = 1; 
for (i in myList[["colNames"]]) { 
    tmpRowNum = myList[["rows"]][[count]]; 
    tmpList = l[[i]]; 
    if (is.null(tmpList)) { 
    tmpList = list(); 
    } 
    l[[i]] = c(tmpList, list(tmpRowNum)) 
    count = count + 1; 
} 

这是行不通的,但因为我是新来的RI,只能假设有一个更有效的方法来做这件事。 with函数创建了两个单独的列表,我必须将它们组合才能得到我期待的结果。

回答

2

你可以尝试:

df <- data.frame(Label1=c("T","F","T"),Label2=c("F","F","T")) 

lapply(df,function(x) which(x=="F")) 

$Label1 
[1] 2 

$Label2 
[1] 1 2 

编辑要获取行的相同,使用apply保证金= 1:

apply(df,1,function(x) which(x=="F")) 

获得 “F” S的矢量第2行:

res <- apply(df,1,function(x) which(x=="F")) 
res[[2]] 
1  2 
+0

正是我需要的...惊人的R和Python可以做一些事情有多短... – scott13

+0

是否有可能,它可以在相反的方向进行?将rownumber映射到它具有错误值的列名称列表? – scott13

+0

@ scott13看我的编辑。 –

0

获取行/列索引的一种有用方法是whicharr.ind

i1 <- which(df=="F", arr.ind=TRUE)