Babak Kasraei
Babak Kasraei

Reputation: 87

Calculating a column from Another column using a condition in R

I have a data frame like;

 
method               SOC
walkley black        0.5
walkley black        1.2
combustion           0.8
combustion           0.7

I want to make a new column called new_SOC. I want to multiply SOC by 10 and put it in new_SOC. I want to do this only for walkley black method and others to be NA.

I made the following codes but I was not successful: I appreciate your help.

## make an empty column called new_SOC
df$new_SOC <- c("")
## Make a loop to calculate the new column with condition.
for (i in 1:length(df)){
   if (df$method == " walkley black")  {
      df$new_SOC = df$SOC*10
      }
   else{df$new_SOC == "NA"}
   }

Upvotes: 0

Views: 999

Answers (3)

akrun
akrun

Reputation: 887851

We can also use case_when

library(dplyr)
df1 <- df %>%
         mutate(new_SOC = case_when(method == "walkley black" ~ SOC * 10))

Or using base R

i1 <- df$method == 'walkley black"
df$new_SOC[i1] <- df$SOC[i1] * 10

Upvotes: 0

Jos&#233;
Jos&#233;

Reputation: 931

Using dplyr, you can:

library(dplyr)
df <- df %>% 
  mutate(new_SOC = ifelse(method == " walkley black", 10*SOC, NA))
  

But, if walkley black is written in different ways:

library(dplyr)
library(stringr)
  df <- df %>% 
  mutate(new_SOC = ifelse(str_detect(method,"walkley black"), 10*SOC, NA))

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 389235

You can use ifelse :

df$new_SOC  <- ifelse(df$method == "walkley black", df$SOC*10, NA)

Upvotes: 0

Related Questions