2

I'm trying to create a for loop that appends a string to each data point in a data frame. I'm using a for loop since the data frame may vary with the number of columns. This is an example of the a possible data frame.

lexicon <- data.frame(
    X.lx = c("word", "word2", "word3"),
    X.ph = c("phonetic", "", "phonetic2")
)

I managed to create a loop that takes the name of the column and appends it to the data points (the data are stored in a data frame lexicon:

for(i in names(lexicon)){
   lexicon[[i]] <- sub("^", paste(names(lexicon[i]), " ", sep=""), lexicon[[i]])
}

This produces:

  X.lx        X.ph
1 X.lx word   X.ph phonetic
2 X.lx word2  X.ph 
3 X.lx word3  X.ph phonetic2

I'm trying to set the loop such as empty data point in the data frame are skipped by sub(), without success. The desired output would be

  X.lx        X.ph
1 X.lx word   X.ph phonetic
2 X.lx word2   
3 X.lx word3  X.ph phonetic2

This is my trial code:

for(i in names(lexicon)){
   lexicon[[i]][which(lexicon[[i]] != "")] <- sub("^", paste(names(lexicon[i]), " ", sep=""), lexicon[[i]][which(lexicon[[i]] != "")])
}

I receive this warning:

Warning messages:
1: In `[<-.factor`(`*tmp*`, which(lexicon[[i]] != ""), value = c(NA_integer_,  :
invalid factor level, NA generated

How can I correctly achieve empty cells to be skipped?

Stefano
  • 1,405
  • 11
  • 21
  • Could you provide some sample data like described in http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example please? – Joris Meys Sep 04 '14 at 13:01
  • 2
    Any specific reason you using a `for` loop here? Please provide `dput(lexicon))` and your desired output – David Arenburg Sep 04 '14 at 13:01

1 Answers1

5
lexicon[] <- mapply(function(x, n) {
  ifelse(x == "", "", paste(n, x))
}, lexicon, names(lexicon))
lexicon
#         X.lx           X.ph
# 1  X.lx word  X.ph phonetic
# 2 X.lx word2               
# 3 X.lx word3 X.ph phonetic2
David Arenburg
  • 91,361
  • 17
  • 137
  • 196
Hong Ooi
  • 56,353
  • 13
  • 134
  • 187