0

I'm trying to loop over certain columns of my dataframe, replacing anything with characters with a 1 (and ignoring blank rows).

data:

df <- structure(list(Participant = 1:3, A = c("a", "a", ""), B = c("", "b", "b"), C = c("c", "c", "c")), .Names = c("Participant", "Q1_1", "Q1_2", "Q1_3"), row.names = c(NA, -3L), class = "data.frame")

If my columns to loop over are:

columns <- c("Q1_1", "Q1_3")

why doesn't this work?

for (i in columns) {
  df$i <- gsub(".+", 1, df$i, perl=TRUE)
}

I'm getting the error:

"Error in `$<-.data.frame`(`*tmp*`, "i", value = character(0)) :replacement has 0 rows, data has 3 
lmcshane
  • 1,074
  • 4
  • 14
  • 27

0 Answers0