Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201977

Reshaping data in R for multiple value types

$
0
0

This is a relatively simple question but I'm having some issues (thank you in advance!). My data looks like this (minimal working example):

df <- data.frame(
  ID = c("A","A","A"),
  org = c("USA","CHN","CHN"),
  partner = c("USA","USA","MEX")
)

> df
  ID org partner
1  A USA     USA
2  A CHN     USA
3  A CHN     MEX

However, I want it to look like this:

df_wide <- data.frame(
  ID = c("A"),
  org1 = c("USA"),
  org2 = c("CHN"),
  partner1 = c("USA"),
  partner2 = c("MEX")
)

> df_wide
  ID org1 org2 partner1 partner2
1  A  USA  CHN      USA      MEX

Note: the data has many rows and IDs. Each ID is associated with an unknown number of origin countries and an unknown number of partner countries. So, for example, I don't want to impose that there are max 2 origin countries per ID.

Additionally, how can I make the data look like this?

df_wide2 <- data.frame(
  ID = c("A")
)
df_wide2$org = list(c("USA","CHN"))
df_wide2$partner = list(c("USA","MEX"))

> df_wide2
  ID      org  partner
1  A USA, CHN USA, MEX

Viewing all articles
Browse latest Browse all 201977

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>