【问题标题】:dplyr mutate_: dynamically create name of columns namesdplyr mutate_:动态创建列名
【发布时间】:2015-12-06 17:32:39
【问题描述】:

我正在努力实现以下目标(尽管我已经阅读了this vignette):

require(dplyr)
require(lazyeval)

# data looks like
df <- data.frame(col1 = c("entry1", "entry2"), col2 = c("0x12", "0xA1"))
#     col1 col2
# 1 entry1 0x12
# 2 entry2 0xA1

# must be something like this:
dots <- list(df %>%
  select(col2) %>%
  distinct(col2))

df %>%
  rowwise() %>% 
  mutate_(.dots = dots)
# target output
#     col1 col2 0x12 0xA1
# 1 entry1 0x12    1  N/A
# 2 entry2 0xA1  N/A    1

所以我想生成一个以单元格条目命名的新列,然后将其设置为一个。这与我迄今为止发现的所有其他示例不同,其中输入列是动态选择的(例如here),或者他们没有使用数据框(but a data.table)。如果 N/A 是 0,它不会造成任何伤害,并为我节省了后处理步骤。

【问题讨论】:

  • 我想这可以使用spreadlibrary(tidyr);df%&gt;% mutate(ind=1, col3=col2) %&gt;% spread(col3, ind) 来完成
  • 您的猜测是正确的 - 非常感谢!你想把它作为答案发布,以便你的努力得到一些分数吗?

标签: r dplyr


【解决方案1】:

这可以通过使用spreadlibrary(tidyr) 重塑为宽格式来轻松解决。我们创建一列 1 ('ind') 和一个副本 'col2' ('col3'),然后使用 spread 来获得预期的输出。

library(tidyr)
df%>% 
  mutate(ind=1, col3=col2) %>% 
  spread(col3, ind)
#     col1 col2 0x12 0xA1
#1 entry1 0x12    1   NA
#2 entry2 0xA1   NA    1

【讨论】:

  • 以防万一有人想知道如何扭转这种情况:使用gather(data, key, value, ..., na.rm = FALSE, convert = FALSE)
猜你喜欢
  • 1970-01-01
  • 2018-10-03
  • 2021-05-14
  • 2022-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-03
  • 2018-11-05
相关资源
最近更新 更多