R:将多个变量合并为一个(有些重叠)

时间:2018-06-20 10:51:41

标签: r merge dplyr multiple-columns

我正在尝试将数据集中的多行合并为一个。我想填写有数据可用的NA,但在有多个条目可用时也要保留各种条目。

数据具有以下结构:

data.frame(ID = c(1,2,3,4), D_1=c("data1",NA,NA,"data1"), D_2= 
c(NA,"data2",NA,NA), D_3 = c("data3",NA,"data3",NA), D_4 = 
c("data4","data4",NA,"data4"), FACT = c("A","B","C","D"))

我发现可以使用的方法要求这些列必须是字符列,所以(我的列也是字符):

 dat$D_1 <- as.character(dat$D_1)
 dat$D_2 <- as.character(dat$D_2)
 dat$D_3 <- as.character(dat$D_3)
 dat$D_4 <- as.character(dat$D_4)

所需的输出: 我想要一列,将其命名为“ D”,它将获得所有可用数据:

Dat$D = (`data1, data3, data4`, `data2, data4`, `data3`, `data1, data4`)

我用过:

 library(dplyr) 

 dat <- dat %>%
 mutate(D = coalesce(D_1, D_2, D_3, D_4))

这是结果:

 dat$D = (data1, data2, data3, data1)

我也尝试过tidyverse中的函数,但是没有运气:

 library(tidyverse)
 dat <- dat1 %>% gather(2, 3) %>%
   filter(value) %>%
   group_by(name) %>%
   summarise(color=paste(key,collapse=",")) %>%
   right_join(dat1)

这给了我一个错误:

 Error in filter_impl(.data, quo) : 
 Evaluation error: object 'value' not found.
 In addition: Warning message:
 attributes are not identical across measure variables;
 they will be dropped 

也尝试过:

D <- with(dat, pmax(D_1, D_2, D_3, D_4))

结果列具有所有不适用值

谢谢

1 个答案:

答案 0 :(得分:0)

df = data.frame(
  ID = c(1, 2, 3, 4),
  D_1 = c("data1", NA, NA, "data1"),
  D_2 = c(NA, "data2", NA, NA),
  D_3 = c("data3", NA, "data3", NA),
  D_4 = c("data4", "data4", NA, "data4"),
  FACT = c("A", "B", "C", "D"),
  stringsAsFactors = FALSE # initial conversion to characters
)

df
#   ID   D_1   D_2   D_3   D_4 FACT
# 1  1 data1  <NA> data3 data4    A
# 2  2  <NA> data2  <NA> data4    B
# 3  3  <NA>  <NA> data3  <NA>    C
# 4  4 data1  <NA>  <NA> data4    D

uniqueData <- unique(c(df$D_1, df$D_2, df$D_3, df$D_4)) # concatenation in vector

uniqueData
# [1] "data1" NA      "data2" "data3" "data4"

uniqueDataNoNA <- uniqueData[!is.na(uniqueData)] # NA removing

uniqueDataNoNA
# [1] "data1" "data2" "data3" "data4"