firmo23
firmo23

Reputation: 8404

How to change the order of list elements?

Hello I created a function which reorders nested elements of a list that way:

library(magrittr)
fun=function(string,NO){
  lapply(strsplit(string,","),function(x) 
    paste(c(by(x, c(s<-rep(1:NO,2),rep(0,length(x)-length(s)))
               ,paste0,collapse=",")),collapse=", "))
}
LIST<-list(list("DC,MD,MA,Baltimore,Washington,Boston,France,China"), list("DC,MD,MA,Baltimore,Washington,Boston,France,China,Turkey"))
rapply(LIST,fun,how="list",NO=3)

How can I modify it to put the city before state?

Upvotes: 0

Views: 390

Answers (1)

De Novo
De Novo

Reputation: 7610

I'd refactor entirely. If you want to rearrange a string with N states followed by N cities, and then put them back in order with city, state, first get pull the string apart entirely.

state_city <- unlist(strsplit(string, ", "))
state <- state_city[1:(length(state_city)/2)]
city <- state_city[(length(state_city)/2 + 1):length(state_city)]
paste(city, state, sep = ", ", collapse = ", ")

as a function:

f <- function(string, NO){
    state_city <- unlist(strsplit(string, ", "))
    state <- state_city[1:(length(state_city)/2)]
    city <- state_city[(length(state_city)/2 + 1):length(state_city)]
    paste(city, state, sep = ", ", collapse = ", ")
}

You don't actually need NO, but i put it in there in case you want to do something else with it.

Upvotes: 1

Related Questions