#This is the example data
dataa <- data.frame(x1 = 1:5, # Create example data
x2 = 6:10,
x3 = 11:15,
x4 = c(1,1,2,2,2))
#Grouped by X4, I want to replace the minimum value in X1:X2 with the minimum value/2, which #means the 1 in X1 and 3 in X1 should be replaced with 0.5 and 1.5; 6 in X2 and 8 in X2 should be #replaced with 3 and 4, respectively.
#Because I will be calculate this in a big data with numerous colomuns, thus maybe I need a FOR #LOOP? However, my codes did not work:
for (j in 1:2)
{
for(i in 1:2)
{
if(dataa[,i]==min(dataa[,i]) & dataa$x4==j) #Wrong
{
dataa[,min(dataa[,i])]<-min(dataa[,i])/(sqrt(2))
}
}
}
#Can you help me?
If it helps, please click accept,Thanks!
try this:
#This is the example data
dataa <- data.frame(x1 = 1:5, # Create example data
x2 = 6:10,
x3 = 11:15,
x4 = c(1,1,2,2,2))
#Grouped by X4, I want to replace the minimum value in X1:X2 with the minimum value/2, which #means the 1 in X1 and 3 in X1 should be replaced with 0.5 and 1.5; 6 in X2 and 8 in X2 should be #replaced with 3 and 4, respectively.
#Because I will be calculate this in a big data with numerous colomuns, thus maybe I need a FOR #LOOP? However, my codes did not work:
for(j in 1:2) {
for(i in 1:2){
tmin=min(dataa[,i][dataa$x4==j])
dataa[,i][dataa[,i]==tmin&dataa$x4==j]<-tmin/2
}
}
dataa
x1 x2 x3 x4
0.5 3 11 1
2.0 7 12 1
1.5 4 13 2
4.0 9 14 2
5.0 10 15 2
您好。上述代码遇到有NA时,不能出正确结果;在不去除有NA的行的前提下,怎么修改代码让其能正确执行?