Reputation: 97
I am trying to change my data frame (names icorr) based on conditions. I want to do this for all the items in the dataframe. I'm quite new to r, and tried the following:
if(icorr<0.01) {icorr <- "***"
} else if(icorr<0.05) {icorr <- "**"
} else if(icorr<0.1) {icorr <- "*"
} else {icorr <- NA}
Definitely doesn't work. Any tips would be great.
Thanks
Upvotes: 0
Views: 75
Reputation: 887881
You could use findInterval
icorr <- c(0.002, 0.05, 0.06, 0.07, 0.1, 0.2, 0.02, 0.3, 0.03,0.049)
c("***","**", "*", NA)[findInterval(icorr, c(-Inf,0.01, 0.05, 0.1, Inf))]
#[1] "***" "*" "*" "*" NA NA "**" NA "**" "**"
Upvotes: 0
Reputation: 51680
You should tell R to select the rows that fit your conditions.
So, for instance:
icorr[icorr < 0.01] <- "***"
This works because icorr<0.01
returns an array of TRUE
and FALSE
, with which you can index your array.
Upvotes: 2
Reputation: 11514
You could try
icorr <- ifelse(icorr<0.01, "***",
ifelse(icorr<0.05, "**",
ifelse( icorr<0.1, "*", NA)))
If this does not work, please provide a reproducable example.
Note that ifelse
is a vectorized version of if
. That is, if you want to do something to a whole vector, ifelse
is probably preferred to if
.
Upvotes: 2