如何重构R中的R数据帧

时间:2017-07-13 22:00:14

标签: r

我有这种格式的数据:

   boss employee1 employee2
1   wil     james      andy
2 james      dean      bert
3 billy      herb    collin
4  tony      mike     david

我希望用这种格式:

   boss employee
1   wil    james
2   wil     andy
3 james     dean
4 james     bert
5 billy     herb
6 billy   collin
7  tony     mike
8  tony    david

我搜索了论坛,但我还没有找到任何有用的东西。我尝试过使用dplyr和其他一些人,但我还是R的新手。

如果这个问题已经得到解答,您可以给我一个非常感谢的链接。

谢谢,

威尔

2 个答案:

答案 0 :(得分:1)

以下是使用tidyr的解决方案。具体来说,gather函数用于组合两个employee列。这也会在列标题(employee1employee2)上生成一个名为key的列。我们从select dplyr删除了library(tidyr) library(dplyr) df <- read.table( text = "boss employee1 employee2 1 wil james andy 2 james dean bert 3 billy herb collin 4 tony mike david", header = TRUE, stringsAsFactors = FALSE ) df2 <- df %>% gather(key, employee, -boss) %>% select(-key) > df2 boss employee 1 wil james 2 james dean 3 billy herb 4 tony mike 5 wil andy 6 james bert 7 billy collin 8 tony david

NSString * storyboardName = @"MainStoryboard"; 
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:storyboardName bundle: nil];
UIViewController * vc = [storyboard instantiateViewControllerWithIdentifier:@"IDENTIFIER_OF_YOUR_VIEWCONTROLLER"];
[self presentViewController:vc animated:YES completion:nil];
如果没有一个更流畅的基础解决方案,我会感到震惊,但这应该对你有用。

答案 1 :(得分:1)

使用基础R:

df1 <- df[, 1:2]
df2 <- df[, c(1, 3)]
names(df1)[2] <- names(df2)[2] <- "employee"
rbind(df1, df2)
#     boss employee
# 1    wil    james
# 2  james     dean
# 3  billy     herb
# 4   tony     mike
# 11   wil     andy
# 21 james     bert
# 31 billy   collin
# 41  tony    david

使用dplyr

df %>% 
  select(boss, employee1) %>% 
  rename(employee = employee1) %>% 
  bind_rows(df %>% 
              select(boss, employee2) %>% 
              rename(employee = employee2))
#    boss employee
# 1   wil    james
# 2 james     dean
# 3 billy     herb
# 4  tony     mike
# 5   wil     andy
# 6 james     bert
# 7 billy   collin
# 8  tony    david

数据:

df <- read.table(text = "
   boss employee1 employee2
1   wil     james      andy
2 james      dean      bert
3 billy      herb    collin
4  tony      mike     david                 
                 ", header = TRUE, stringsAsFactors = FALSE)