你好我创建了一个函数,它以一种方式重新排序列表的嵌套元素:
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)
如何修改它以将城市置于州之前?
答案 0 :(得分:1)
我完全重构了。如果你想重新排列一个N个状态后跟N个城市的字符串,然后将它们按顺序放回城市,状态,首先将字符串完全拉开。
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 = ", ")
作为一个功能:
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 = ", ")
}
你实际上并不需要NO
,但我会把它放在那里,以防你想用它做其他事情。