-2

I wrote a code in R To do some change in a text after count the number of character And if the number of character grater than 5 do the change And it is working here is my code

dataset<-  c ("there is a rain " , "I am student" )
dataset <-data.frame(x= dataset)
dataset $x<-as.character(dataset $x)
words <- unlist(strsplit(dataset $x, " "))
nchar(words)
K <- character(length(words))
K[nchar(words) < 6] <- words[nchar(words) < 6]
K[nchar(words) > 5] <- gsub('e', 'X', 
                            words[nchar(words) > 5], perl = TRUE)

the result

[1] "there"   "is"      "a"       "rain"    "I"       "am"      "studXnt"

As you can see it do the change but my problem is that It merge between the texts So If I have 50 rows then I do not know the text belong of which row Because at the end I need to save the change on original text

The result I expect

[1] There is a rain 
[2] I am studXnt

Thank you

Reem
  • 47
  • 8
  • 2
    Please fix your code. There are "smart-quotes" (not good for R) and incorrect syntax. – r2evans Dec 27 '18 at 08:36
  • 1
    @r2evans sorry I fix it – Reem Dec 27 '18 at 08:44
  • Can you explain the title of this question? I see nothing that suggests merging, you are really just dealing with a vector of strings, and I think you are changing the 5th letter of 5+ long words, nothing to "save" here. – r2evans Dec 27 '18 at 08:44
  • as you can see (student) change to (studXnt) – Reem Dec 27 '18 at 08:46
  • 2
    As I saw and suggested at the end of the comment, yes. At the beginning of that comment, though, I asked about the title. Confusing and/or completely-unrelated titles can make it hard to understand what the heck the question is really about, therefore slowing down or stopping an answer altogether. Asking a good question is very much (1) making it easy to understand (clarity in the title and content), and (2) making it easy for people to test (sample data, packages, your reduced code that is syntactically correct ... minimal working example). – r2evans Dec 27 '18 at 08:50
  • And though it is your right to choose not to do so, it is a *courtesy* (good etiquette) on StackOverflow to [accept an answer](https://stackoverflow.com/help/someone-answers) (or the best/first if multiple are provided). I suggest you go back and do so for [each of your previous questions](https://stackoverflow.com/users/9549309/reem) (I've [suggested this before](https://stackoverflow.com/questions/49782567/the-output-result-does-not-change-when-enter-different-input-in-shiny-r#comment87023329_49782760)). – r2evans Dec 27 '18 at 09:04

1 Answers1

1

Here is the correct syntax to do it,

sapply(strsplit(df$x, ' '), function(i){i[nchar(i) > 5] <- gsub('e', 'X', i[nchar(i) > 5]);
                                        paste(i, collapse = ' ')})

#[1] "there is a rain" "I am studXnt"
Sotos
  • 47,396
  • 5
  • 31
  • 61