簡體   English   中英

在多列上使用 tidyr 的 pivot_wider 的問題

[英]Problems using tidyr's pivot_wider on multiple columns

我正在嘗試使用 tidyr 中的 pivot_wider 函數同時轉置兩種值,如小插圖('pivot')下的“每行多個觀察”示例所示,但我不斷收到奇怪的錯誤消息。

這是正在發生的事情的一個例子:

set.seed(5)
testdat <- data.frame(matrix(nrow=5,ncol=5))
colnames(testdat) <- c('rating','percent.Female','percent.Male','se.Female','se.Male')
testdat$rating <- c('Very good','Good','OK','Bad','Very bad')
testdat$percent.Female <- rnorm(5,.5,.2)
testdat$percent.Male <- 1 - testdat$percent.Female
testdat$se.Female <- rnorm(5,0.1,0.003)
testdat$se.Male <- rnorm(5,0.1,0.003)
testdat
     rating percent.Female percent.Male  se.Female    se.Male
1 Very good      0.3318289    0.6681711 0.09819128 0.10368289
2      Good      0.7768719    0.2231281 0.09858350 0.09759466
3        OK      0.2489016    0.7510984 0.09809389 0.09675882
4       Bad      0.5140286    0.4859714 0.09914268 0.09952740
5  Very bad      0.8422882    0.1577118 0.10041432 0.09678472
testdat %>% pivot_longer(cols=-"rating",names_sep=".",names_to=c(".value","gender"),values_drop_na=T)
 Error: Expected a vector, not NULL Call `rlang::last_error()` to see a backtrace In addition: Warning message: Expected 2 pieces. Additional pieces discarded in 4 rows [1, 2, 3, 4]

我幾乎完全按照小插圖 - 為什么這不起作用?

由於選項names_sep="." (您會注意到在樞軸小插圖中,名稱由 _ 而不是 . 分隔。)

. 是用於匹配任何單個字符的特殊字符。 如果要指定變量名稱由實際的. 字符本身,您需要使用names_sep="\\\\." 逃避它。

轉義到位后,示例如下:

testdat %>% 
  pivot_longer(cols=-"rating", names_sep="\\.", 
               names_to=c(".value","gender"), values_drop_na=TRUE)
# A tibble: 10 x 4
   rating    gender percent     se
   <chr>     <chr>    <dbl>  <dbl>
 1 Very good Female   0.332 0.0982
 2 Very good Male     0.668 0.104 
 3 Good      Female   0.777 0.0986
 4 Good      Male     0.223 0.0976
 5 OK        Female   0.249 0.0981
 6 OK        Male     0.751 0.0968
 7 Bad       Female   0.514 0.0991
 8 Bad       Male     0.486 0.0995
 9 Very bad  Female   0.842 0.100 
10 Very bad  Male     0.158 0.0968

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM