Swapping a value of 0 for the value next to it in R

I have data.frame

one that looks like this:

Variable_1=c(123,0,12,0,334)
Variable_2=c(100,212,13,112,300)
df=data.frame(Variable_1,Variable_2)

      

Ideally, I would like to replace the values 0

in Variable_1

with the adjacent value from Variable_2

in order to get the following:

Variable_1=c(123,212,12,112,334)
Variable_2=c(100,212,13,112,300)

      

I've tried the following:

df$Variable_1[df$Variable_1 == 0] <- df$Variable_2

      

The problem I'm running into is my result:

Variable_1=c(123,100,12,212,334)
Variable_2=c(100,212,13,112,300)

      

+3


source to share


2 answers


You also need to multiply the RHS of your assignment expression.



df$Variable_1[df$Variable_1 == 0] <- df$Variable_2[df$Variable_1 == 0]

      

+3


source


You can also use ifelse

for this:



df <- data.frame(
  Variable_1 = c(
    123,0,12,0,334),
  Variable_2 = c(
    100,212,12,112,300))
##
df$Variable_1 <- ifelse(
  df$Variable_1==0,
  df$Variable_2,
  df$Variable_1)
##
> df
  Variable_1 Variable_2
1        123        100
2        212        212
3         12         12
4        112        112
5        334        300

      

+1


source







All Articles