【问题标题】:Adding columns to Large Tibbles将列添加到大标题
【发布时间】:2020-11-23 03:35:44
【问题描述】:

我在将列添加到大的 tibble 时遇到了困难。我使用的代码适用于一个小的模拟 tibble,如下所示。我遇到的问题是当我在我的大 tibble 上使用它时。 500 obs. of 100 variables,它添加了列,但只是将它们固定在末尾,而不是放在我指定的位置。

>RecordId <- c(1, 2, 3, 4, 5)
>Name <- c("a", "b", "c", "d", "e")
>
>theTibble <- tibble(RecordId, Name)
>
>
>theTibble <- add_column(theTibble, a = NA, .before = theTibble$RecordId )
>theTibble <- add_column(theTibble, Month = NA, .before = theTibble$RecordId)
>theTibble <- add_column(theTibble, `Month#` = "23", .before = theTibble$RecordId )
>theTibble$Month <- replace(theTibble$Month, is.na(theTibble$Month), "NOV");
>theTibble
# A tibble: 5 x 5
  `Month#` Month a     RecordId Name 
  <chr>    <chr> <lgl>    <dbl> <chr>
1 23       NOV   NA           1 a    
2 23       NOV   NA           2 b    
3 23       NOV   NA           3 c    
4 23       NOV   NA           4 d    
5 23       NOV   NA           5 e 

【问题讨论】:

  • 放置参数需要带引号的列名或列索引 - 您正在传递一个向量,它似乎将向量中的最小值作为索引。我很惊讶它没有抛出错误。试试add_column(theTibble, a = NA, .before = "RecordId" )

标签: r dplyr


【解决方案1】:

如果您想在开头而不是结尾添加列,您可以使用cbind。另外我不明白为什么您首先将Month 列为NA,然后将所有NA 值替换为'NOV',您可以直接分配'NOV'

result <- cbind(`Month#` = 23, Month = 'NOV', a = NA, theTibble)
result

#  Month# Month  a RecordId Name
#1     23   NOV NA        1    a
#2     23   NOV NA        2    b
#3     23   NOV NA        3    c
#4     23   NOV NA        4    d
#5     23   NOV NA        5    e

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-19
    • 2014-05-26
    • 2012-01-03
    • 2012-06-21
    • 2019-04-04
    • 2018-10-17
    • 1970-01-01
    相关资源
    最近更新 更多