Home > Software engineering >  How to update a cell in R coresponding to a value in the first column row in R Programming
How to update a cell in R coresponding to a value in the first column row in R Programming

Time:01-18

How to change a value in a cell along the same row in r programming?

I have a text delimited file and narrowed the columns to V1 and v2.

V1   V2
123  23
133  44
222  55

data2 <- data[-c(-1,-2)]

Now I want to change the value in the second column cell for a specific number let's say 133.

Basically for 133 in column v1 I want the cell adjacent to it to be changed to 999. How do I do that?

I have tried:

data4 <- data2[data2$v1==133,V2] <-999

But no luck with it.

CodePudding user response:

So, in your code V1was in lowercase, and R is case sensitive. Also V2 wasn't in brackets.

Code

data <- data.frame(V1 = c(123,133,222), V2 = c(23,44,55))

data[data$V1==133,"V2"] <- 999

data

Output

   V1  V2
1 123  23
2 133 999
3 222  55

CodePudding user response:

We could use ifelse:

library(dplyr)
df %>% 
  mutate(V2 = ifelse(V1 == 133, 999, V2))
   V1  V2
1 123  23
2 133 999
3 222  55
  •  Tags:  
  • r
  • Related