r - 在多列上使用 tidyr 的 pivot_wider 的问题

标签 r dplyr reshape tidyr

我正在尝试使用 tidyr 的 pivot_wider 函数同时转置两种值,如 vignette('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

关于r - 在多列上使用 tidyr 的 pivot_wider 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60559808/

相关文章:

python - View 中的 Numpy reshape

r - 在 knitr 中缓存子文件

r - 检查 R 中的日期是否为空?

r - 创建一个虚拟变量列来指示记录是否位于第二个数据帧中?

r - 基于阈值的汇总表

python - Pandas 部分转置

python - 无效参数错误 : Incompatible shapes with Keras LSTM Net

根据R中的多个条件删除数据框中的行

R:使用 ddply 将函数应用于数据子集

r - 您可以使用 dplyr cross() 来遍历成对的列吗?