Replacing values from a column using a condition in R

RDataframeConditional Statements

R Problem Overview


I have a very basic R question but I am having a hard time trying to get the right answer. I have a data frame that looks like this:

 ind<-rep(1:4,each=24)
 hour<-rep(seq(0,23,by=1),4)
 depth<-runif(length(ind),1,50)

 df<-data.frame(cbind(species,ind,hour,depth))
 df$depth<-as.numeric(df$depth)

What I would like it to select AND replace all the rows where depth < 10 (for example) with zero, but I want to keep all the information associated to those rows and the original dimensions of the data frame.

I have try the following but this does not work.

df[df$depth<10]<-0

Any suggestions?

R Solutions


Solution 1 - R

# reassign depth values under 10 to zero
df$depth[df$depth<10] <- 0

(For the columns that are factors, you can only assign values that are factor levels. If you wanted to assign a value that wasn't currently a factor level, you would need to create the additional level first:

levels(df$species) <- c(levels(df$species), "unknown") 
df$species[df$depth<10]  <- "unknown" 

Solution 2 - R

I arrived here from a google search, since my other code is 'tidy' so leaving the 'tidy' way for anyone who else who may find it useful

library(dplyr)
iris %>% 
  mutate(Species = ifelse(as.character(Species) == "virginica", "newValue", as.character(Species)))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1626688View Question on Stackoverflow
Solution 1 - RMattBaggView Answer on Stackoverflow
Solution 2 - RstevecView Answer on Stackoverflow