Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing values from a column using a condition in R

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:

species <- "ABC"
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?

like image 233
user1626688 Avatar asked Dec 14 '12 01:12

user1626688


People also ask

How do you replace values in a column in R based on condition?

1. Replace Values Based on Condition in R. Replace column values based on checking logical conditions in R DataFrame is pretty straightforward. All you need to do is select the column vector you wanted to update and use the condition within [] .

How do I replace a word in a column in R?

Use str_replace_all() method of stringr package to replace multiple string values with another list of strings on a single column in R and update part of a string with another string.


2 Answers

# 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" 
like image 124
MattBagg Avatar answered Oct 07 '22 18:10

MattBagg


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

like image 21
stevec Avatar answered Oct 07 '22 19:10

stevec