Suppose I have a dataset:
test = data.frame(x=c(1:11), y=as.character(c(1:11)))
where the collumn ‘y’ is made up of characters/strings.
Now, I would like to change the strings containing two characters (i.e. test[10,2] & test[11,2]) so that those strings start with a character “0”. The result of this would be “010” & “011”, whereas the other strings (with only one character) remain the same.
To me, the logical solution would be:
test[nchar(test[,2])==2,2] = paste(c("0", test[nchar(test[,2])==2,2]), collapse="")
Indeed, only test[10,2] & test[11,2] are affected. The odd thing is though, that the result is test[10,2] = “01011”, and test[11,2] = “01011”. This means that all strings having two characters are pasted together with a preceding “0”. This definitely is not what I would like to see.
What should I do to add only one character to a string in a dataset when certain conditions (of length) are met?
Your answer would be greatly appreciated.
use
so for example
collapseandsephave different properties