A B
0 1
0 0
1 0
我有一個設計矩陣,其中我的前兩列「A」和「B」是由0和1填充我需要替換這兩個列與一個總結他們兩個即,即。在一個新的總體列1將在影響A和B之一是1的地方,一個0,其中他們都爲0。
我嘗試如下:
x <- vector("list", length(my_mat)) #empty vector
for(i in 1:length(design[2])) #fill vector with column content
ifelse(attempt[ ,1]==1|attempt[ ,2]==1, x[i]<-design[i], x[i]<-0) #in event that either A or B is 1 give x vector a 1 other wise give it a 0
as.matrix(x)
my_mat<-my_mat[ ,-c(1,2)] #get rid of first two columns
my_mat<-cbind(my_mat, x) #summarise first two columns by binding the other new one
我問題是,我得到的矢量是充滿NULL值,所以我做錯了,因爲它應該只是做了一個向量0和1的
注意我希望能夠訪問與「$」注意,但我得到以下錯誤,因爲原始數據不是數據框: 設計錯誤$ Culture_confirmed_TB: $操作是原子向量
進行我想你想'as.integer(rowSums(M [,C( 「A」, 「B」)])> 0L)'或' as.integer(m [,「A」] + m [,「B」]> 0L)'或'pmax(m [,「A」],m [,「B」])'? – Frank
另一個標準的解決方案是'answer < - apply(matrixName,1,max)',儘管它比'rowSums'慢。 – lmo
非常感謝你的第一個建議幫助 –