Change Values in Row Based on a Column Value R

Change values in row based on a column value and replacing specified column range

Try:

x[x$Month %in% c("March", "April"), c("VAR2", "VAR3")] = NA

Change values in row based on a column value r

how about:

x[x$C <10 ,] <- NA

Update row values based on condition in R

A super easy base solution

df <- data.frame(cue=sample(c(1:3),10,replace = T),c2=sample(c(0,1),10,replace = T),c3=sample(c(0,1),10,replace = T))

df$c2 <- ifelse(df$cue==2,1,0)
df$c3 <- ifelse(df$cue==3,1,0)

EDIT

to add another dplyr solution

df <- dplyr::mutate(df,c2= ifelse(cue==2,1,0),c3= ifelse(cue==3,1,0))

Change row value based on another column in DataFrame using dplyr

Instead of filtering and then joining we can directly use mutate_at with case_when

library(dplyr)
df %>%
mutate_at(vars(col2, col3), ~
case_when(col1 == 'b' ~ .* 10, col1 == 'c' ~ .* 20, TRUE ~ .))
# col1 col2 col3
#1 a 2 5
#2 b 40 100
#3 a 6 15
#4 c 160 400
#5 b 100 250
#6 c 240 600

Or in the dplyr 1.0.0, it can be done with mutate/across

df %>%
mutate(across(c(col2, col3), ~
case_when(col1 == 'b' ~ .* 10, col1 == 'c' ~ .* 20, TRUE ~ .)))
# col1 col2 col3
#1 a 2 5
#2 b 40 100
#3 a 6 15
#4 c 160 400
#5 b 100 250
#6 c 240 600

Update column rows based on rows in another column

There are several options:

Base R - Option 1

mydf$Description[mydf$Value == 0] <- "TEST"

Base R - Option 2

mydf$Description <- ifelse(mydf$Value == 0, "TEST", mydf$Description)

dplyr - if_else()

library("dplyr")
mydf <- mydf %>% mutate(Description = if_else(Value == 0, "TEST", Description))

dplyr - case_when()

Useful when a number of if statement need to be evaluated.

library("dplyr")
mydf <- mydf %>% mutate(
Description = case_when(
Value == 0 ~ "TEST",
TRUE ~ Description
)
)

R - change values in multiple selected rows based on multiple conditional column

Here is an alternative way without loop:

have <- have %>% mutate(cond = col1 == "A" & col2 == "B", id = 1:nrow(have))
met <- have %>% filter(cond == TRUE) %>%
mutate(col3 = "C", col4 = paste(cyl, hp, sep = ","))
have[met$id,] <- met


Related Topics



Leave a reply



Submit