pdench
pdench

Reputation: 41

If TRUE in one column, change value in other column

I have a character vector: (shortened version shown)

Unit <- c("e10", "e11", "10e10", "10e11")

I want to apply the following condition: if the value start with 'e', replace 'e' with '10e' so that the final vector will look something like this:

"10e10" "10e11" "10e10" "10e11"

I used startsWith() to create a TRUE/FALSE vector:

startsWith.e <- startsWith(Unit, "e")

This gives TRUE TRUE FALSE FALSE.

Lastly, I want to run a for or while loop (or some kind of conditional), so that when startsWith.e is TRUE, values 'e' in Unit are replaced with '10e'.

while(startsWith.e){
grep("e", "10e", Unit) }

However, I get stuck in an infinite loop and using an if statement says it will only evaluate the first statement (and therefore change all cases because it will evaluate TRUE).

Hope someone can help!

Upvotes: 1

Views: 88

Answers (4)

zwep
zwep

Reputation: 1340

(My answer is redundant... @akrun already solved it with sub )

Why not use gsub..?

Unit <- c("e10", "e11", "10e10", "10e11")
gsub("^e","10e",Unit)
[1] "10e10" "10e11" "10e10" "10e11"

Upvotes: 0

what_alnk
what_alnk

Reputation: 81

If you want to use for, like this (but this is longer version of lmo's answer):

Unit <- c("e10", "e11", "10e10", "10e11")
startsWith.e <- startsWith(Unit, "e")
for (i in 1:length(Unit)) {
 if (startsWith.e[i]) {
    Unit[i] <- paste0("10", Unit[i])
  }
}
Unit
#> [1] "10e10" "10e11" "10e10" "10e11"

Upvotes: 0

lmo
lmo

Reputation: 38520

Using startsWith and subsetting, you could do

Unit[startsWith(Unit, "e")] <- paste0("10", Unit[startsWith(Unit, "e")])

which returns

Unit
[1] "10e10" "10e11" "10e10" "10e11"

Upvotes: 1

akrun
akrun

Reputation: 887741

We can use sub for this. Match the letter 'e' at the start (^) of the string and replace with '10e'

sub("^e", "10e", Unit)
#[1] "10e10" "10e11" "10e10" "10e11"

Upvotes: 4

Related Questions