I want to change the values of column based on an if-else conditions and am using FOR loop to do that. The data is shown below:
我想根据if-else条件更改列的值,并使用FOR循环来实现这一点。数据如下:
m1 m2 m3 a1 a2
0.5 0.7 0.2 10 20
0.1 0 0.2 30 40
I want to apply the following condition
我想应用以下条件。
ifelse(column > 0.5,1,0)
I tried using this code, but its not working:
我试过用这个代码,但是没用:
for (k in 1:3){
data$m[k] <- ifelse(data$m[k] > 0.5,1,0)
}
I also tried using double square brackets [[ ]], but that's also not working. I used the same logic for a list which worked fine, but in this case the column names are string and am not sure how to change the code accordingly.
我也尝试过使用双方括号[],但也不起作用。我对一个运行良好的列表使用了相同的逻辑,但是在这种情况下,列名是字符串,我不知道如何相应地更改代码。
1 个解决方案
#1
0
See bellow code, i think you will expecting this...
看看下面的代码,我想你会期待这个…
m<-data.frame(
m1=c(0.5,0.1),
m2=c(0.7,0),
m3=c(0.2,0.2),
a1=c(10,30),
a2=c(20,40)
)
for(i in 1:3){
m[,i]<-ifelse(m[,i]>0.5,1,0)
}
result is:
结果是:
m1 m2 m3 a1 a2
0 1 0 10 20
0 0 0 30 40
#1
0
See bellow code, i think you will expecting this...
看看下面的代码,我想你会期待这个…
m<-data.frame(
m1=c(0.5,0.1),
m2=c(0.7,0),
m3=c(0.2,0.2),
a1=c(10,30),
a2=c(20,40)
)
for(i in 1:3){
m[,i]<-ifelse(m[,i]>0.5,1,0)
}
result is:
结果是:
m1 m2 m3 a1 a2
0 1 0 10 20
0 0 0 30 40