如何将具有相同行名的行合并为一个

时间:2018-09-13 13:32:18

标签: r

我的数据框如下:

if(birthdayfdb() == "sunday") check = true;

我希望将其转换为仅保留product<-c("ab","ab","ab","ac","ac") HD<-c("12","","","","") HS<-c("","23","","","") HR<-c("","","34","","") HO<-c("","","","23","") DF<-c("","","","","24") store22<-data.frame(product,HD,HS,HR,HO,DF) product HD HS HR HO DF 1 ab 12 2 ab 23 3 ab 34 4 ac 23 5 ac 24 的唯一值的方式,从而将这些值放在同一行中,如下所示:

product

3 个答案:

答案 0 :(得分:1)

product<-c("ab","ab","ab","ac","ac")
HD<-c("12","","","","")
HS<-c("","23","","","")
HR<-c("","","34","","")
HO<-c("","","","23","")
DF<-c("","","","","24")
store22<-data.frame(product,HD,HS,HR,HO,DF)

library(tidyverse)

store22 %>%
  mutate(product = as.character(product)) %>% # update to character variable
  gather(x,y,-product) %>%                    # reshape data
  filter(y != "") %>%                         # exclude rows where y is empty
  spread(x,y, fill="")                        # reshape again and replace NAs with empty values

#   product DF HD HO HR HS
# 1      ab    12    34 23
# 2      ac 24    23 

答案 1 :(得分:1)

Image

data.table

答案 2 :(得分:1)

我们可以在字符变量上使用max

library(dplyr)

store22 %>%
  group_by(product) %>%
  summarize_all(~max(as.character(.)))

输出:

# A tibble: 2 x 6
  product HD    HS    HR    HO    DF   
  <fct>   <chr> <chr> <chr> <chr> <chr>
1 ab      12    23    34    ""    ""   
2 ac      ""    ""    ""    23    24