Home > Mobile >  Exchange empty cells for the number 0 in R
Exchange empty cells for the number 0 in R

Time:10-21

How do I exchange empty cells for the number 0 in my database below. I know it is possible to do: df1[df1==""]<-0, in this case it checks all columns in my database, however I would like it to be checked from the column DR01. I thought of something like this: df1 %>% select(starts_with("DR0")=="")<-0, but it didn't work.

df1 <- structure(
  list(Date = c("30-06-2021","01-07-2021","02-07-2021","03-07-2021"),
       DR1 = c(4,1,4,1),
       DR01 = c(4,1,4,2), DR02= c(4,2,6,2),DR03= c(9,5,4,2),
       DR04 = c(5,4,3,3),DR05 = c(5,4,5,""),
       DR06 = c(2,4,3,""),DR07 = c(2,5,4,""),
       DR08 = c(0,0,0,""),DR09 = c(0,0,0,""),DR010 = c(0,0,0,""),DR011 = c(4,0,0,""), 
       DR012 = c(0,0,0,""), DR013 = c(0,0,1,""), DR014 = c(0,0,0,"")),
  class = "data.frame", row.names = c(NA, -4L))

> df1
        Date DR1 DR01 DR02 DR03 DR04 DR05 DR06 DR07 DR08 DR09 DR010 DR011 DR012 DR013 DR014
1 30-06-2021   4    4    4    9    5    5    2    2    0    0     0     4     0     0     0
2 01-07-2021   1    1    2    5    4    4    4    5    0    0     0     0     0     0     0
3 02-07-2021   4    4    6    4    3    5    3    4    0    0     0     0     0     1     0
4 03-07-2021   1    2    2    2    3

> class(df1)
[1] "tbl_df"     "tbl"        "data.frame"

CodePudding user response:

Base solution:

df = structure(
  list(Date = c("30-06-2021","01-07-2021","02-07-2021","03-07-2021"),
       DR1 = c(4,1,4,1),
       DR01 = c(4,1,4,2), DR02= c(4,2,6,2),DR03= c(9,5,4,2),
       DR04 = c(5,4,3,3),DR05 = c(5,4,5,""),
       DR06 = c(2,4,3,""),DR07 = c(2,5,4,""),
       DR08 = c(0,0,0,""),DR09 = c(0,0,0,""),DR010 = c(0,0,0,""),DR011 = c(4,0,0,""), 
       DR012 = c(0,0,0,""), DR013 = c(0,0,1,""), DR014 = c(0,0,0,"")),
  class = "data.frame", row.names = c(NA, -4L))

# Select columns that will be modified
# save into variable, because we will use it a few times
selection = startsWith(names(df), "DR0")
df[selection][df[selection] == ""] = 0

CodePudding user response:

Another solution:

df1[,-(1:2)][df1[,-(1:2)]==""] <- 0

CodePudding user response:

In dplyr you may use across -

library(dplyr)

df1 %>% mutate(across(starts_with('DR0'), ~replace(., . == '', 0)))

#        Date DR1 DR01 DR02 DR03 DR04 DR05 DR06 DR07 DR08 DR09 DR010 DR011 DR012 DR013 DR014
#1 30-06-2021   4    4    4    9    5    5    2    2    0    0     0     4     0     0     0
#2 01-07-2021   1    1    2    5    4    4    4    5    0    0     0     0     0     0     0
#3 02-07-2021   4    4    6    4    3    5    3    4    0    0     0     0     0     1     0
#4 03-07-2021   1    2    2    2    3    0    0    0    0    0     0     0     0     0     0
  •  Tags:  
  • r
  • Related