简体   繁体   中英

Issues with replacing a subset of a data.frame using the R Package dplyr

I am trying to replace some filtered values of a data set. So far, I wrote this lines of code:

df %>%
  filter(group1 == uniq[i]) %>%
  mutate(values = ifelse(sum(values) < 1, 2, NA)),

where uniq is just a list containing variable names I want to focus on (and group1 and values are column names). This is actually working. However, it only outputs the altered filtered rows and does not replace anything in the data set df. Does anyone have an idea, where my mistake is? Thank you so much! The following code is to reproduce the example:

group1 <- c("A","A","A","B","B","C")
values <- c(0.6,0.3,0.1,0.2,0.8,0.9)
df = data.frame(group1, group2, values)
uniq <- unique(unlist(df$group1))

for (i in 1:length(uniq)){
  df <- df %>%
  filter(group1 == uniq[i]) %>%
    mutate(values = ifelse(sum(values) < 1, 2, NA))
}

What I would like to get is that it leaves all values except the last one since it is one unique group (group1 == C) and 0.9 < 1. So I'd like to get the exact same data frame here except that 0.9 is replaced with NA. Moreover, would it be possible to just use if instead of ifelse?

dplyr won't create a new object unless you use an assignment operator ( <- ).

Compare

require(dplyr)
data(mtcars)

mtcars %>% filter(cyl == 4)

with

mtcars4 <- mtcars %>% filter(cyl == 4)
mtcars4

The data are the same, but in the second example the filtered data is stored in a new object mtcars4

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