Reputation: 189
I have an input called target and a dataframe:
target <- 3
d <- data.frame(x=c(1,2,3),y=c(4,5,6))
x y
1 4
2 5
3 6
I want for each row:
if the value of column x < target then this value <- 0
if the value of column y > target then this value <- 9
the result:
x y
0 9
0 9
3 9
how could I get this?
I tried to use the function apply
but it didn't allow to modify the value in dataframe d
.
Upvotes: 0
Views: 1578
Reputation: 2473
A straighforward way only using R base.
# Add object.
target <- 3
# Create dataframe.
df1 <- data.frame(x = c(1, 2, 3),y=c(4, 5, 6))
# Copy dataframe [df1] to new dataframe [ðf2].
# Preserve old dataframe [df1] for comparison.
df2 <- df1
# Insert digits.
df2$x[df2$x < target] <- 0
df2$y[df2$y > target] <- 9
Upvotes: 0
Reputation: 230
With dplyr and case_when:
library(dplyr)
d <- d %<%
mutate(target = 3,
x = case_when(x < target ~ 0,
T ~ x),
y = case_when(y > target ~ 9,
T ~ y))
With base r:
d$x[d$x < target,] <- 0
d$y[d$y > target,] <- 9
Upvotes: 0
Reputation: 388807
Multiple ways to do this. One way using double replace
replace(replace(d, d > target, 9), d < target, 0)
# x y
#1 0 9
#2 0 9
#3 3 9
This logic can also be used in dplyr
chain
library(dplyr)
d %>% mutate_all(funs(replace(replace(., . > target, 9), . < target, 0)))
Upvotes: 1