R:将一列的行追加到相邻列

时间:2019-05-02 18:04:23

标签: r dplyr tidyverse tidyr

我想将同一数据帧中两列的行绑定在一起。目前,我是通过将它们合并并拆分来实现的。有没有更简洁的方法?

enter image description here

enter image description here

library(tidyverse)
library(splitstackshape)

Citrus_1 <- c("Lemon", "Lime", "Orange")
Citrus_2 <- c("Grapefruit", NA, NA) 
Fruit_List <- data.frame(Citrus_1, Citrus_2)

Fruit_List %>%
  unite(Citrus_List, c("Citrus_1", "Citrus_2"), sep = ",") %>%
  cSplit(., "Citrus_List", sep = ",", direction = "long") %>%
  filter(!is.na(Citrus_List))

编辑:列名选择不当。更新为Citrus_List

2 个答案:

答案 0 :(得分:2)

使用tidyverse方法:

您的数据:

Citrus_1 <- c("Lemon", "Lime", "Orange")
Citrus_2 <- c("Grapefruit", NA, NA) 
Fruit_List <- data.frame(Citrus_1, Citrus_2)

列表为数据框,只有一列:

Fruit_List %>% 
        gather("Citrus_1", "Citrus_2", key = "Fruit_var",value = "Citrus_List",na.rm = TRUE) %>% 
        select(Citrus_List)

答案 1 :(得分:1)

我们可以使用base R来做到这一点。 unlist的“水果列表”,删除NAna.omit)并创建一个data.frame

data.frame(Fruit_list = na.omit(unlist(Fruit_List, use.names = FALSE)))
#  Fruit_list
#1      Lemon
#2       Lime
#3     Orange
#4 Grapefruit