R spread函数(错误...选择未定义的列)

R spread function (error in ... undefined columns selected)

我用谷歌搜索了我的错误,但这对我没有帮助。

获得了一个数据框,其中包含 x 列。

unique(df$x) 

结果是:

[1] "fc_social_media"         "fc_banners"              "fc_nat_search"          
[4] "fc_direct"               "fc_paid_search"

当我尝试这个时:

df <- spread(data = df, key = x, value = x, fill = "0") 

我收到错误:

Error in `[.data.frame`(data, setdiff(names(data), c(key_var, value_var))) : 
undefined columns selected

但这很奇怪,因为我(在同一个脚本中)多次使用了 spread 函数。

所以我用谷歌搜索,看到了一些 "solutions":

@Gregor,@Akrun:

    > str(df)
'data.frame':   100 obs. of  22 variables:
 $ visitor_id             : chr  "321012312666671237877-461170125342559040419" "321012366667112237877-461121705342559040419" "321012366661271237877-461170534255901240419" "321012366612671237877-461170534212559040419" ...
 $ visit_num              : chr  "1" "1" "1" "1" ...
 $ ref_domain             : chr  "l.facebook.com" "X.co.uk" "x.co.uk" "" ...
 $ x                      : chr  "fc_social_media" "fc_social_media" "fc_social_media" "fc_social_media" ...
 $ va_closer_channel      : chr  "Social Media" "Social Media" "Social Media" "Social Media" ...
 $ row                    : int  1 2 3 4 5 6 7 8 9 10 ...
 $                        : chr  "0" "0" "0" "0" ...
 $ Hard Drive             : chr  "0" "0" "0" "0" ...

错误可能是由于列没有名称,即 ""。使用可重现的例子

library(tidyr)
spread(df, x, x)

Error in [.data.frame(data, setdiff(names(data), c(key_var, value_var))) : undefined columns selected

我们可以通过更改列名使其工作

names(df) <- make.names(names(df))
spread(df, x, x, fill = "0")
#   X fc_banners fc_direct fc_nat_search fc_paid_search fc_social_media
#1 1          0         0             0              0 fc_social_media
#2 2 fc_banners         0             0              0               0
#3 3          0         0 fc_nat_search              0               0
#4 4          0 fc_direct             0              0               0
#5 5          0         0             0 fc_paid_search               0

数据

df <- data.frame(x =  c("fc_social_media",  "fc_banners", 
   "fc_nat_search", "fc_direct", "fc_paid_search"), x1 = 1:5, stringsAsFactors = FALSE)
names(df)[2] <- ""