I'm getting data from a web source with rvest
and then I got a vector, say x
, which has a length different from my other vectors (so I can't combine them into a table). Getting to the point: The reason is that every time I see the element 'nuovo'
(position x[11]
) in the vec, I know It should be pasted with exactly the previous, then i should also cancel out the element 'nuovo' because I need a 25 length vector.
x = c("Vetrina" ,"Vetrina" ,"Vetrina",
"Vetrina" ,"Vetrina", "Vetrina",
"Vetrina" ,"Vetrina" ,"Vetrina",
"Vetrina" ,"nuovo" ,"Vetrina",
"Vetrina" ,"Vetrina" ,"Vetrina",
"Vetrina" ,"Vetrina" ,"Vetrina",
"Vetrina" ,"Vetrina", "Vetrina",
"Vetrina" ,"Vetrina", "Vetrina",
"Vetrina" ,"Vetrina")
length(x) = 26
and then I need x
to be like:
x = c("Vetrina" ,"Vetrina" ,"Vetrina",
"Vetrina" ,"Vetrina", "Vetrina",
"Vetrina" ,"Vetrina" ,"Vetrina",
"Vetrina nuovo","Vetrina",
"Vetrina" ,"Vetrina" ,"Vetrina",
"Vetrina" ,"Vetrina" ,"Vetrina",
"Vetrina" ,"Vetrina", "Vetrina",
"Vetrina" ,"Vetrina", "Vetrina",
"Vetrina" ,"Vetrina")
length(x) = 25
You can use this:
# First find the elements we wish to remove
nuovo = which(x=="nuovo")
x = x[-nuovo]
# Now paste into the preceding elements.
nuovo2 = nuovo - seq_along(nuovo)
x[nuovo2] = paste(x[nuovo2], "nuovo")
Similarly, you could instead reverse the order of these operations and paste before removing
x[nuovo - 1] = paste(x[nuovo - 1], "nuovo")
x = x[-nuovo]
Here is a solution in base
R. First you get the position of nuovo
then paste
it to the previous position. Finally you remove nuovo
positions.
x <- c("Vetrina" ,"Vetrina" ,"Vetrina",
"Vetrina" ,"Vetrina", "Vetrina",
"Vetrina" ,"Vetrina" ,"Vetrina",
"Vetrina" ,"nuovo" ,"Vetrina",
"Vetrina" ,"Vetrina" ,"Vetrina",
"Vetrina" ,"Vetrina" ,"Vetrina",
"Vetrina" ,"Vetrina", "Vetrina",
"Vetrina" ,"Vetrina", "Vetrina",
"Vetrina" ,"nuovo")
pos <- x == "nuovo"
x[c(pos[-1], F)] <- paste(x[c(pos[-1], F)], "nuovo")
x <- x[!pos]
length(x)
> 24
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With