Make change to a data frame and save the changed data frame as a new data frame in R

Viewed 99

I am trying to replace all the negative values in a data frame with zero, and I also want to keep the original data frame with negative values. Here's my attempt with sample data:

col1 <- c("-1", "2", "-3", "0", "10")
col2<- c("1", "2", "3", "4", "5")
col3<- c("1", "-2", "3", "-4", "-5")
uncleaned.data <- data.frame(col1, col2, col3)

cleaned_data <- uncleaned.data[uncleaned.data<0]=0

I got an error like this object 'cleaned_data' not found Any suggestions? Intuitively I don't see any issues here .. Thanks a lot!

4 Answers

In the code, there are two assignments. i.e. =0 is an assignment and clean_data is not initialized. We just need a copy of the original data as 'cleaned_data' and then do the replacement on that dataset

cleaned_data <- uncleaned.data
cleaned.data[cleaned.data < 0] <- 0

This solution can also be used:

library(dplyr)

uncleaned.data %>% 
  rowwise() %>%
  mutate(across(everything(), ~ ifelse(as.numeric(.x) < 0, "0", .x)))

# A tibble: 5 x 3
# Rowwise: 
  col1  col2  col3 
  <chr> <chr> <chr>
1 0     1     1    
2 2     2     0    
3 0     3     3    
4 0     4     0    
5 10    5     0 

It seems you need replace

cleaned_data <- replace(uncleaned.data, uncleaned.data < 0, 0)

such that

> cleaned_data
  col1 col2 col3
1    0    1    1
2    2    2    0
3    0    3    3
4    0    4    0
5   10    5    0
library(tidyverse)
library(stringr)

#preparing data
col1 <- c("-1", "2", "-3", "0", "10")
col2 <- c("1", "2", "3", "4", "5")
col3 <- c("1", "-2", "3", "-4", "-5")

uncleaned.data <- data.frame(col1, col2, col3)

#solution

uncleaned.data |> 
    map_dfr(~str_replace(.x, '-[0-9]+$', '0'))
#> # A tibble: 5 x 3
#>   col1  col2  col3 
#>   <chr> <chr> <chr>
#> 1 0     1     1    
#> 2 2     2     0    
#> 3 0     3     3    
#> 4 0     4     0    
#> 5 10    5     0

#optional

uncleaned.data |> 
    map_dfr(~str_replace(.x, '-[0-9]+$', '0')) %>% 
    mutate_all(as.numeric)
#> # A tibble: 5 x 3
#>    col1  col2  col3
#>   <dbl> <dbl> <dbl>
#> 1     0     1     1
#> 2     2     2     0
#> 3     0     3     3
#> 4     0     4     0
#> 5    10     5     0

Created on 2021-06-08 by the reprex package (v2.0.0)

Related