在R中,如果构造的数据帧具有未知数量的列和行,那么将如何执行行方式或列方式布尔操作。
此代码构造了这样的数据帧。
{ family: 4 }
假设随机数据帧为3x3。
nrows <- sample(3:10, 1)
ncolumns <- sample(3:10, 1)
random.boolean.matrix <- matrix(lapply(seq(1:(nrows*ncolumns)), function(x){sample(0:1,1)}), ncol=ncolumns)
random.boolean.dataframe <- as.data.frame(random.boolean.matrix)
如何执行每行的AND以使输出为:
> random.boolean.dataframe
V1 V2 V3
1 1 1 0
2 1 0 0
3 1 1 1
答案 0 :(得分:1)
您可以使用rowMeans
:
v=ifelse(rowMeans(random.boolean.dataframe)==1,1,0)
[1] 0 0 1
或apply
,例如:
v=apply(random.boolean.dataframe,1,min)
[1] 0 0 1
答案 1 :(得分:1)
使用rowSums
:
as.numeric(!rowSums(!random.boolean.dataframe))
# [1] 0 0 1
答案 2 :(得分:1)
您可以使用any
> set.seed(1984)
> mx <- as.data.frame(matrix(sample(0:1,100, replace = T), ncol = 10))
>
> mx
V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
1 1 1 1 1 1 1 0 0 1 1
2 0 0 0 0 0 0 1 1 0 1
3 0 1 1 1 1 1 0 1 1 0
4 0 1 1 1 0 0 0 1 0 1
5 1 0 1 0 0 1 1 0 0 1
6 1 0 0 0 1 0 1 1 0 1
7 0 0 1 1 1 0 1 0 0 0
8 0 1 1 0 0 0 0 0 0 1
9 1 1 1 0 0 1 1 1 1 1
10 0 0 1 0 1 0 0 1 1 0
>
> ## for the 'AND' operator
>
> sapply(mx, function(x) as.numeric(any(x == 0)))
V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
1 1 1 1 1 1 1 1 1 1
>
> ## for the 'OR' operator
>
> sapply(mx, function(x) as.numeric(any(x != 0)))
V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
1 1 1 1 1 1 1 1 1 1
>
答案 3 :(得分:1)
这是其中一个问题,我所寻找的答案就是所有答案。
rowAnd <- function(dataframe, columns = 1:ncol(dataframe)){
sapply(seq(1:nrows),function(x) ifelse(all(dataframe[x,columns] == 1),1,0))
}
rowOr <- function(dataframe, columns = 1:ncol(dataframe)){
sapply(seq(1:nrows),function(x) ifelse(any(dataframe[x,columns] == 1),1,0))
}
columnAnd <- function(dataframe, rows = 1:nrow(dataframe)){
sapply(seq(1:nrows),function(x) ifelse(all(dataframe[rows,x] == 1),1,0))
}
columnOr <- function(dataframe, rows = 1:nrow(dataframe)){
sapply(seq(1:nrows),function(x) ifelse(any(dataframe[rows,x] == 1),1,0))
}
rowAnd (random.boolean.dataframe)
rowOr (random.boolean.dataframe)
columnAnd (random.boolean.dataframe)
columnOr (random.boolean.dataframe)