R:在tidyr扩散函数中使用向量作为关键参数

时间:2018-04-19 22:22:46

标签: r data-manipulation tidyr spread

我正在尝试使用tidyr扩展功能,除了我想传递我自己的功能名称向量以用于关键参数。

例如,默认用法为

test<-data.frame(id=c(1,1,2,2),
             feat=c("feat1", "feat2", "feat1", "feat2"),
             value = c(10,20, 1000, 2000))
test %>% spread(key = feat, value = value, fill = 0)
  id feat1 feat2
1  1    10    20
2  2  1000  2000

我想传递我自己的特征字符串向量来用作键,就像这样。

featlist<-c("feat1", "feat2", "feat3")
test %>% spread(key = featlist, value = value, fill = 0)
#desired output
  id feat1 feat2 feat3
1  1    10    20     0
2  2  1000  2000     0
#Error output
Error: `var` must evaluate to a single number or a column name, not a character vector
#Trying spread_
test %>% spread_(key = featlist, value = "value", fill = 0)
Error: Only strings can be converted to symbols

2 个答案:

答案 0 :(得分:4)

只需将专栏列设为水平设置为featlist的因子,然后将drop参数设置为FALSE,如下所示:

test<-data.frame(id=c(1,1,2,2),
                 feat=c("feat1", "feat2", "feat1", "feat2"),
                 value = c(10,20, 1000, 2000))

featlist<-c("feat1", "feat2", "feat3")
test$feat <- factor(test$feat, levels = featlist)

test %>% spread(key = feat, value = value, fill = 0, drop = FALSE)

结果是:

  id feat1 feat2 feat3
1  1    10    20     0
2  2  1000  2000     0

答案 1 :(得分:1)

不幸的是,tidyr::spread不允许将您自己的vector用作key,但幸运的是expand.grid为您提供了使用您自己vectordata.frame的选项。在调用spread函数之前展开library(tidyverse) expand.grid(id=unique(test$id), feat = featlist) %>% #creates all combinations mutate(feat = as.character(feat)) %>% left_join(test, by=c("id", "feat")) %>% #Join with actual dataframe spread(key=feat, value = value, fill = 0) # id feat1 feat2 feat3 #1 1 10 20 0 #2 2 1000 2000 0

test<-data.frame(id=c(1,1,2,2),
                 feat=c("feat1", "feat2", "feat1", "feat2"),
                 value = c(10,20, 1000, 2000), stringsAsFactors = FALSE)

featlist<-c("feat1", "feat2", "feat3")

数据:

mybucketname/
      class_1/
          img001.jpg
          img002.jpg
          ...
      class_2/
          img001.jpg
          img002.jpg
          ...
      class_3/
          img001.jpg 
          img002.jpg
          ...