1

In RStudio. Not sure how to replace blanks from certain columns only - and based on their names. Have tried many version of

census_data[c("NAICSP","SOCP") == ""] <- NA
NelsonGon
  • 13,015
  • 7
  • 27
  • 57
Dianna Li
  • 121
  • 6
  • 2
    Hi Dianna Li. By adding a [minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610#5963610)you can help others to help you! You said you tried "many versions" : Have you tried `census_data[census_data$NAICSP %in% "", "NAICSP"] <- NA` ? What was the output? – dario Feb 22 '20 at 07:02
  • Replaces all blanks in the file, instead of just the two columns. – Dianna Li Feb 23 '20 at 05:49
  • Edit: That actually worked. Looked at the wrong columns. However, I'm not familiar with what the $ and %in% portions do. – Dianna Li Feb 23 '20 at 06:01
  • Current Code: census_data[census_data$NAICSP %in% "", "NAICSP"] <- NA census_data[census_data$SOCP %in% "", "SOCP"] <- NA – Dianna Li Feb 23 '20 at 06:07

2 Answers2

2

You may try using apply in column mode, for a base R option:

cols <- c("NAICSP","SOCP")
census_data[, cols] <- apply(census_data[, cols], 2, function(x) {
    ifelse(x == "", NA, x)
})
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

Disclaimer: This answer uses mde, a package that I happen to have written. If one is open to using packages, one can use recode_as_na from mde and provide a subset_cols vector as follows:

census_data<- data.frame(ID = c("A","B","B","A"),
                         NAICSP = c("",NA,"Yes","No"),
                          SOCP = c("","","",""))
 # install.packages("devtools")
 # devtools::install_github("Nelson-Gon/mde")
 mde::recode_as_na(census_data,subset_df=TRUE,
                   subset_cols = c("NAICSP","SOCP"),
                   value="")
  ID NAICSP SOCP
1  A   <NA>   NA
2  B   <NA>   NA
3  B    Yes   NA
4  A     No   NA
Warning message:
In recode_as_na.data.frame(census_data, subset_df = TRUE, subset_cols = c("NAICSP",  :
  Factor columns have been converted to character

NOTE:

The warning message is to remind users of behind the scenes coercion to character.

NelsonGon
  • 13,015
  • 7
  • 27
  • 57