简体   繁体   中英

How to transpose a data frame in R in a way that the elements of a character variable become columns in the new data frame

Here's an example of a data frame I am using.

ID <- c(1,1,2,3)
Type <- c('A', 'B', 'A', 'A')
Value <- c(2.5, 8, 10, 7)
df <- data.frame(ID,Type,Value)
df

And here's how df looks like:

ID Type Value
1 A 2.5
1 B 8.0
2 A 10.0
3 A 7.0

I'm looking for a way to transpose df in a way that the elements of the character variable "Type" become columns in the new data frame.

ID A B
1 2.5 8
2 10.0 0
3 7.0 0

Note that for IDs 2 and 3, where only type A values are present in df, I'd like to have zero values under column B in the new data frame.

We can use pivot_wider

library(dplyr)
library(tidyr)
df %>%
   pivot_wider(names_from = Type, values_from = Value, values_fill = 0)

-output

# A tibble: 3 × 3
     ID     A     B
  <dbl> <dbl> <dbl>
1     1   2.5     8
2     2  10       0
3     3   7       0

data

df <- data.frame(ID, Type, Value)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM