【问题标题】:Creating two new columns from two different columns in R?从R中的两个不同列创建两个新列?
【发布时间】:2021-03-10 16:51:29
【问题描述】:

我有一个这种格式的 df,其中我有具有不同关联数据 (fieldID) 和值 (value) 的相同项目。

itemID fieldID value
1 1 Title
1 6 2019 - 03 - 00
2 1 Title 2
2 6 May 26, 2020
3 1 Title 3
3 6 March 2019

而我想做的是创建一个这样的表

itemID Date Title
1 2019 - 03 - 00 Title
2 May 26, 2020 Title 2
3 March 2019 Title 3

不知道如何尝试。我一直在研究 mutate 函数并在谷歌上搜索根据条件创建新列,但需要一些额外的帮助......

【问题讨论】:

  • 查看spread 函数,例如关于长到宽转换的教程:rstudio-pubs-static.s3.amazonaws.com/…
  • 为什么不写一个基于spread 的解决方案呢?这应该是一个相当不错的学习体验,并且是对其他可能答案的一个很好的附加选择
  • 太好了,感谢您提供的资源。我不知道这个!

标签: r dplyr


【解决方案1】:

将值 1 重新编码为“标题”,将值 6 重新编码为“日期”,并将数据转换为宽格式。

library(dplyr)
library(tidyr)

df %>%
  mutate(fieldID = recode(fieldID, '1' = 'Title', '6' = 'Date')) %>%
  pivot_wider(names_from = fieldID, values_from = value)

#  itemID Title   Date          
#   <int> <chr>   <chr>         
#1      1 Title   2019 - 03 - 00
#2      2 Title 2 May 26, 2020  
#3      3 Title 3 March 2019    

数据

df <- structure(list(itemID = c(1L, 1L, 2L, 2L, 3L, 3L), fieldID = c(1L, 
6L, 1L, 6L, 1L, 6L), value = c("Title", "2019 - 03 - 00", "Title 2", 
"May 26, 2020", "Title 3", "March 2019")), 
row.names = c(NA, -6L), class = "data.frame")

【讨论】:

    【解决方案2】:

    这行得通吗:

    library(dplyr)
    df %>% select(-fieldID) %>% filter(row_number()%%2 == 0 ) %>% inner_join(
     df %>% select(-fieldID) %>% filter(row_number()%%2 != 0 ), by = 'itemID'
     ) %>% select(itemID, 'Date' = value.x, 'Title' = value.y)
    # A tibble: 3 x 3
      itemID Date           Title  
       <dbl> <chr>          <chr>  
    1      1 2019 - 03 - 00 Title  
    2      2 May 26, 2020   Title 2
    3      3 March 2019     Title 3
    

    使用的数据:

    df
    # A tibble: 6 x 3
      itemID fieldID value         
       <dbl>   <dbl> <chr>         
    1      1       1 Title         
    2      1       6 2019 - 03 - 00
    3      2       1 Title 2       
    4      2       6 May 26, 2020  
    5      3       1 Title 3       
    6      3       6 March 2019    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-25
      • 1970-01-01
      • 1970-01-01
      • 2018-03-03
      • 1970-01-01
      • 2018-10-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多