2012-06-28 57 views
0

我有一個data.frame數值。如何與0 因此,例如在一排替換每行最大:用0代替最大行數

10,1,3,4

輸出將是

0,1 ,3,4

我嘗試:

df1 <- data.frame(df)[apply(df,1,which.max=0)] 

但我有什麼問題。

我會很感激您的幫助。

回答

3

如何

replace_max <- function(x){x[which.max(x)] <- 0;x} 

t(apply(df, 1, replace_max)) 

library(plyr) 
adply(df, 1, replace_max) 

編輯做行

編輯:2確保data.frame

+0

非常感謝你。 plyr非常好。 –

2

這是我會怎麼做:

a <-matrix(round(runif(25)*100,0),ncol=5) #create matrix 
my.max <-apply(a,1,which.max) #find max position by row 

>  a 
    [,1] [,2] [,3] [,4] [,5] 
[1,] 62 14 19 64 40 
[2,] 74 83 26 95 14 
[3,] 32 69 24 12 67 
[4,] 100 57 19 3 16 
[5,] 41 6 93 85 67 


z <-cbind(1:5,my.max) #create coordinates 
a[z] <-0 #replace those entries 
>  a 
    [,1] [,2] [,3] [,4] [,5] 
[1,] 62 14 19 0 40 
[2,] 74 83 26 0 14 
[3,] 32 0 24 12 67 
[4,] 0 57 19 3 16 
[5,] 41 6 0 85 67 
1

試試這個:

#Generating a fake dataframe: 
    df=data.frame(A=c(1:5), B=c(6,111,5,7,10), C=c(11,28,65,7,15) , D=c(21:25)) 
> df 
    A B C D 
1 1 6 11 21 
2 2 111 28 22 
3 3 5 65 23 
4 4 7 7 24 
5 5 10 15 25 

n=length(rownames(df)) 
for(i in 1:n){ 
c1=as.numeric(which.max(df[i,])) 
df[i,c1]=0 

} 


df #output 
    A B C D 
1 1 6 11 0 
2 2 0 28 22 
3 3 5 0 23 
4 4 7 7 0 
5 5 10 15 0 
1

如何:

x <- matrix(sample(1:16),nrow=4) 

x 
    [,1] [,2] [,3] [,4] 
[1,] 1 12 6 4 
[2,] 16 2 13 15 
[3,] 11 8 10 7 
[4,] 14 9 5 3 

x*as.logical(x-apply(x,1,max)) 
    [,1] [,2] [,3] [,4] 
[1,] 1 0 6 4 
[2,] 0 2 13 15 
[3,] 0 8 10 7 
[4,] 0 9 5 3 
相關問題