【问题标题】:include character and numeric values dataframe [duplicate]包括字符和数值数据框[重复]
【发布时间】:2020-11-10 23:56:57
【问题描述】:

我有一个数据框,其中包含一列 0 和 1,标记为“捕获”。我想将其转换为 Y 和 N,但将其保存在我稍后用于打印 kable 的数据框中。我怎样才能成功地混合这样的变量类型?

ï..video capture point     x     y   c.2..cm. speed..cm.s. speedB..cm.s.
1       23       0     1 4.972 1.138         NA           NA            NA
2       23       0     2 4.970 1.145 0.00728011    0.2184033      6.552099
3       23       0     3 4.989 1.154 0.02102380    0.6307139     18.921416
4       23       0     4 4.973 1.140 0.02126029    0.6378087     19.134262
5       23       0     5 4.993 1.145 0.02061553    0.6184658     18.553975
6       23       0     6 5.000 1.129 0.01746425    0.5239275     15.717824

如果有帮助,这也是我的 kable 的代码。

reduced.rounded.summary %>%
  kable(caption = "Multiple Copepod Interactions", font_size = 12) %>%
  kable_styling(full_width = F, position = "float_right") %>%
  add_header_above(c(" " = 2, "Mouth" = 3))

【问题讨论】:

    标签: r rscript


    【解决方案1】:

    如果您有一列 0 和 1,则向其中添加 1 会得到一列 1 和 2s。这些可以用来下标简单向量c("No", "Yes")

    reduced.rounded.summary %>% mutate(capture = c("No", "Yes")[capture + 1])
    #>   ï..video capture point     x     y   c.2..cm. speed..cm.s. speedB..cm.s.
    #> 1       23      No     1 4.972 1.138         NA           NA            NA
    #> 2       23      No     2 4.970 1.145 0.00728011    0.2184033      6.552099
    #> 3       23      No     3 4.989 1.154 0.02102380    0.6307139     18.921416
    #> 4       23      No     4 4.973 1.140 0.02126029    0.6378087     19.134262
    #> 5       23      No     5 4.993 1.145 0.02061553    0.6184658     18.553975
    #> 6       23      No     6 5.000 1.129 0.01746425    0.5239275     15.717824
    

    【讨论】:

    • 谢谢,艾伦。这似乎应该工作,但它给了我一个错误说“无效的下标类型'列表'”
    • @BetsyPotter 我的回答中的示例只是获取您在示例中提供的数据并将其称为reduced.rounded.summary。你能确认这确实是一个数据框,并且它有一个名为capture 的列是数字吗?
    • 这只是超过 1000 行的数据帧的头部。数据框确实有一个名为“capture”的列,它是数字,只有 0 和 1。
    • @BetsyPotter 那么如果你这样做 reduced.rounded.summary$capture + 1 会得到什么?你应该得到一个 1s 和 2s 的数字向量。
    • 打印一系列1和2。
    【解决方案2】:

    一个简单的ifelse 操作就可以了:

    df <- data.frame(
      capture = c(0,1,1,0,1,0,0,0,1,0)
    )
    
    df$capture <- ifelse(df$capture==1, "yes", "no")
    df
       capture
    1       no
    2      yes
    3      yes
    4       no
    5      yes
    6       no
    7       no
    8       no
    9      yes
    10      no
    

    【讨论】:

      猜你喜欢
      • 2021-10-04
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      • 2017-03-22
      • 1970-01-01
      • 2015-01-03
      • 2019-10-20
      • 1970-01-01
      相关资源
      最近更新 更多