简体   繁体   中英

Select data from a dataframe and then create new df with 0 and 1 by matched values in R

I need help with this problem in R. I have this dataframe, is bigger than the example, but follow this structure:

id   group score
ft12 a     0
ft13 b     1
ft14 c     2

so I want to get a new dataframe (output) that has 1 for the matched value and 0 for the mismatched value like this:

id   group_a  group_b group_c  score_0 score_1  score_2 
ft12 1         0        0        1       0         0
ft13 0         1        0        0       1         0
ft14 0         0        1        0       0         1

Note: the number of groups and score is fixed(just group a,b,c) and score (0,1,2) I would appreciate any help, thanks in advance!

One possibility is to use the fastDummies package.

library(fastDummies) 
dummy_cols(myData, select_columns =c("group", "score" ) , remove_selected_columns =True)

For more details you can check this page .

Here's a way to do this in tidyverse :

library(dplyr)
library(tidyr)

df %>%
  mutate(across(everything(), as.character)) %>%
  #In old dplyr use mutate_all
  #mutate_all(as.character)
  pivot_longer(cols = -id) %>%
  mutate(n = 1) %>%
  pivot_wider(names_from = c(name, value) ,values_from = n, 
              values_fill = list(n = 0))


# A tibble: 3 x 7
#  id    group_a score_0 group_b score_1 group_c score_2
#  <chr>   <dbl>   <dbl>   <dbl>   <dbl>   <dbl>   <dbl>
#1 ft12        1       1       0       0       0       0
#2 ft13        0       0       1       1       0       0
#3 ft14        0       0       0       0       1       1

data

df <- structure(list(id = c("ft12", "ft13", "ft14"), group = c("a", 
"b", "c"), score = 0:2), class = "data.frame", row.names = c(NA, -3L))

We can use table from base R

table(c(df$id[row(df[-1])]), unlist(df[-1]))

#     0 1 2 a b c
#ft12 1 0 0 1 0 0
#ft13 0 1 0 0 1 0
#ft14 0 0 1 0 0 1

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