Reputation:
I'm trying to add a Fav column in x, which gives app if x2 is more than 50%. But, i don't get any column added. please help.
x<- data.frame(x1=c(1,2,3,4,5),x2=c(2,3,4,5,6),x3=c(3,2,5,2,5))
x$x2per <- (x$x2/(x$x2+x$x3))*100
x$x3per <- (x$x3/(x$x2+x$x3))*100
if(x$x2per>50){
x$Fav <- "App"
}
else x$Fav<-"LF"
I get the below output.
Warning message:
In if (x$x2per > 50) { :
the condition has length > 1 and only the first element will be used
> x
x1 x2 x3 x2per x3per
1 1 2 3 40.00000 60.00000
2 2 3 2 60.00000 40.00000
3 3 4 5 44.44444 55.55556
4 4 5 2 71.42857 28.57143
5 5 6 5 54.54545 45.45455
>
Upvotes: 0
Views: 30
Reputation: 70653
Or you could assign all observations one value and then overwrite in case they meet your criteria on x2per
.
x$Fav <- "LF"
x$Fav[x$Fav > 50] <- "App"
If you want your if
loop to work, you will need to use indexing.
x$Fav <- NA
for (i in 1:nrow(x)) {
if(x$x2per[i] > 50) {
x$Fav[i] <- "App"
}
} else {
x$Fav[i] <- "LF"
}
}
Upvotes: 1
Reputation: 5893
Use ifelse
for vectorized if statement
x$Fav <- ifelse(x$x2per > 50, "APP", "LF")
Upvotes: 2