【问题标题】:reshape to wide with empty column returns only one observation [duplicate]用空列重塑为宽仅返回一个观察值[重复]
【发布时间】:2018-01-08 15:26:02
【问题描述】:

我注意到一个空列最终会导致仅观察。有人可以向我解释这种行为吗?我应该在继续之前查找并删除空列吗?

testdf <- CO2[,c("Plant","conc","Treatment","uptake")]

testdf$Plant <- gsub("c","n",testdf$Plant)

works <- reshape(
  testdf,
  idvar = c(
    "Plant",
    "conc"
  ),
  timevar = "Treatment",
  direction = "wide"
)

testdf$Problem <- as.numeric(NA)

notworking <- reshape(
  testdf,
  idvar = c(
    "Plant",
    "conc",
    "Problem"
  ),
  timevar = "Treatment",
  direction = "wide"
)

【问题讨论】:

  • 另见my answer here,它显示了使用addNA 的帮助(不删除“问题”列)——它引用了reshape 函数中的同一行。

标签: r reshape


【解决方案1】:

reshape 代码中的第 '94' 行可能会导致问题

...
data[, tempidname] <- interaction(data[, idvar], 
            drop = TRUE)
...

使用'testdf'

interaction(testdf[, c("Plant", "conc", "Problem")], drop = TRUE)
# [1] <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA>
#[23] <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA>
#[45] <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA>
#[67] <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA>
#Levels: 

结果是所有NA

删除“问题”列

interaction(testdf[, c("Plant", "conc")], drop = TRUE)
#[1] Qn1.95   Qn1.175  Qn1.250  Qn1.350  Qn1.500  Qn1.675  Qn1.1000 Qn2.95   Qn2.175  Qn2.250  Qn2.350  Qn2.500 
#[13] Qn2.675  Qn2.1000 Qn3.95   Qn3.175  Qn3.250  Qn3.350  Qn3.500  Qn3.675  Qn3.1000 Qn1.95   Qn1.175  Qn1.250 
#[25] Qn1.350  Qn1.500  Qn1.675  Qn1.1000 Qn2.95   Qn2.175  Qn2.250  Qn2.350  Qn2.500  Qn2.675  Qn2.1000 Qn3.95  
#[37] Qn3.175  Qn3.250  Qn3.350  Qn3.500  Qn3.675  Qn3.1000 Mn1.95   Mn1.175  Mn1.250  Mn1.350  Mn1.500  Mn1.675 
#[49] Mn1.1000 Mn2.95   Mn2.175  Mn2.250  Mn2.350  Mn2.500  Mn2.675  Mn2.1000 Mn3.95   Mn3.175  Mn3.250  Mn3.350 
#[61] Mn3.500  Mn3.675  Mn3.1000 Mn1.95   Mn1.175  Mn1.250  Mn1.350  Mn1.500  Mn1.675  Mn1.1000 Mn2.95   Mn2.175 
#[73] Mn2.250  Mn2.350  Mn2.500  Mn2.675  Mn2.1000 Mn3.95   Mn3.175  Mn3.250  Mn3.350  Mn3.500  Mn3.675  Mn3.1000
#42 Levels: Mn1.95 Mn2.95 Mn3.95 Qn1.95 Qn2.95 Qn3.95 Mn1.175 Mn2.175 Mn3.175 Qn1.175 Qn2.175 Qn3.175 ... Qn3.1000

替代方法包括来自reshape2data.tabledcast

data.table::dcast(testdf, Plant + conc + Problem ~ Treatment, value.var = 'uptake')

spread 来自tidyr

library(tidyr)
spread(testdf, Treatment, uptake)

【讨论】:

  • 感谢 akrun,dcast 按预期工作。我需要学习如何调试函数。
猜你喜欢
  • 2016-07-08
  • 2021-11-11
  • 1970-01-01
  • 2020-05-01
  • 1970-01-01
  • 2020-04-15
  • 1970-01-01
相关资源
最近更新 更多