Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to paste together a vector element with the previuos according to a condition

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
like image 612
Nicco_per_Firenze Avatar asked Jan 26 '23 03:01

Nicco_per_Firenze


2 Answers

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]
like image 125
dww Avatar answered Jan 28 '23 16:01

dww


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
like image 43
Clemsang Avatar answered Jan 28 '23 16:01

Clemsang