1

I would like to convert a dataframe containing zip codes and relationships between zip codes into a list.

I looked at ways to convert dataframes into lists as well as the spread function.

The first column (codes1) contains all zip codes of a zone. The second column (codes2) contains the zip codes of the cities related to the first one.

df<-as.data.frame(cbind(rep(1:4, c(2,5,4,3)),c(2,4,4,3,6,8,7,1,2,8,7,1,2,3)))
colnames(df)<-c("codes1","codes2")
df

I would like to obtain a list like this one, containing for each zip code the related zip codes:

l <- list(c(2,4), c(4,3,6,8,7),c(1,2,8,7),c(1,2,3))
l
0

1 Answer 1

3

You could just split codes2 by codes1

split(x = df$codes2, f = df$codes1)
#$`1`
#[1] 2 4

#$`2`
#[1] 4 3 6 8 7

#$`3`
#[1] 1 2 8 7

#$`4`
#[1] 1 2 3

You could also loop through unique values of codes1 and select relevant value from codes2

lapply(X = unique(df$codes1),
       FUN = function(x) subset(df$codes2, df$codes1 == x))
#[[1]]
#[1] 2 4

#[[2]]
#[1] 4 3 6 8 7

#[[3]]
#[1] 1 2 8 7

#[[4]]
#[1] 1 2 3
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.