简体   繁体   中英

modify value in each row of a dataframe

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 .

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)))

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM