将列表列表中的元素替换为基于 if 条件与 R 在不同数据框中找到的元素

Replace elements in a list of lists with elements found on different dataframe based on if condition with R

我有一个列表列表,其中包含美国各州的全名。

l1<-list(list(c("Arizona")),list(c("California")),list(c("Texas","California","Alabama")))

我想要做的是用我在不同数据集中的州首字母缩写词替换全名。

data("state.fips" )
state.fips<-data.frame(state.fips)

为了在 state.fips 中将每个州的首字母转换为大写并创建新列 COL2 我使用了:

firstup <- function(x) {
      substr(x, 1, 1) <- toupper(substr(x, 1, 1))
      x
    }

state.fips$polyname<- firstup(state.fips$polyname)

state.fips$COL2 <- gsub("([A-Za-z]+).*", "\1", state.fips$polyname)

然后我创建一个新的空列表:

l2 <- vector('list', 3)

我尝试用基于 state.fips 数据集的州首字母缩写词替换州的全名:

for(i in 1:3){
   l2[[i]]<-lapply(l1[[i]], function(x)x[which(x %in% state.fips[j,7] )])
   for(j in 1:63){
     if(sapply(l2[[i]], function(x) length(x) > 0)==TRUE){
       l2[[i]]<-gsub(l1[[i]],state.fips[j,5],l1[[i]])
     }
     else{
       l2[[i]]<-l1[[i]]
     }
   }}

显然它不起作用,更具体地说,在具有多个名称的列表中它甚至不执行替换。有什么建议么?

首先,你不仅有一个列表中的列表,还有另一个向量。这也许就是为什么你只替换了第一个 'element'.

我建议使用 2 lapply 和 sapply。

l2 <- lapply(l1, function(sublist){ # iterates over the first list
  lapply(sublist, function(state.vector){ # iterates over the second list inside the first list
    sapply(state.vector, function(state){ # iterates over the vectors inside the second list
      return(state.fips[which(state.fips[,'COL2'] == state),'abb']) # select the abbreviation based on the statename in COL2
    })
  })
})