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?