Nicco_per_Firenze
Nicco_per_Firenze

Reputation: 86

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

Upvotes: 4

Views: 86

Answers (3)

dww
dww

Reputation: 31454

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]

Upvotes: 3

Clemsang
Clemsang

Reputation: 5491

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

Upvotes: 3

tmfmnk
tmfmnk

Reputation: 40181

One possibility involving lag() from dplyr():

x <- ifelse(lag(x, default = first(x)) == "nuovo", paste(x, lag(x)), x)
x[-grepl("nuovo", x)]

 [1] "Vetrina"       "Vetrina"       "Vetrina"       "Vetrina"       "Vetrina"      
 [6] "Vetrina"       "Vetrina"       "Vetrina"       "Vetrina nuovo" "Vetrina"      
[11] "Vetrina"       "Vetrina"       "Vetrina"       "Vetrina"       "Vetrina"      
[16] "Vetrina"       "Vetrina"       "Vetrina"       "Vetrina"       "Vetrina"      
[21] "Vetrina"       "Vetrina"       "Vetrina"       "Vetrina"  

Upvotes: 2

Related Questions