Question Details

No question body available.

Tags

r reshape missing-data long-format-data wide-format-data

Answers (4)

Accepted Answer Available
Accepted Answer
April 20, 2026 Score: 2 Rep: 34,872 Quality: Medium Completeness: 40%

Probably a duplicate question but here is a solution using data.table:

library(data.table)

setDT(df) dcast(df, ID ~ region, fill = 0)

ID A B

1: 1 1 NA

2: 2 1 1

3: 3 NA 0

April 20, 2026 Score: 4 Rep: 273,987 Quality: Medium Completeness: 80%

1) Sticking with the framework in the question replace each NA in the input with NaN. Then we can distinguish the type of missing value as NaN (missing value coming from input) or NA (missing value resulting from reshape):

res  ftable2df()

ID A B
1 1 1 NA
2 2 1 1
3 3 NA 0
April 20, 2026 Score: 2 Rep: 12,253 Quality: Low Completeness: 60%

With rapidly fast {collapse} API

collapse::pivot( data=X, ## assigned your df to X how='w', ## shorthand for 'wider' name='region', values='status', fill=0 ## or NaN )

ID A B 1 1 1 NA 2 2 1 1 3 3 NA 0
April 20, 2026 Score: 1 Rep: 427 Quality: Low Completeness: 40%

tidyr::pivotwider() does exactly what you want via valuesfill:

library(tidyr)

pivotwider( df, idcols = ID, namesfrom = region, valuesfrom = status, values_fill = 0 )

Output:

# A tibble:
     ID     A     B

1 1 1 0 2 2 1 1 3 3 NA 0