我有一个带数值的data.frame。如何用0替换每行最大值 例如,连续一行:
10,1,3,4
输出将是
0,1,3,4
我试过了:
df1 <- data.frame(df)[apply(df,1,which.max=0)]
但我有些不对劲。
我很感激你的帮助。
答案 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
答案 1 :(得分: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
答案 2 :(得分: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
答案 3 :(得分: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