首页 > 解决方案 > R 变异(Dataframe 与 Tibble)

问题描述

在 R 3.6.1 (64) 位中工作。使用 readxl 将数据框放入 R 中(命名为“RawShift”。我制作了 6 个变量(类:“字符”),它们是用户名列表。每个列表都以用户所在的团队命名。

我想使用 Mutate 创建一个包含用户所在团队的列。

INTeam = C("user1", "user2",...)
OFTeam = C("user3", "user4",...)

当我一直在使用数据框时,此代码有效:

RawShift <- RawShift %>% mutate(Team =case_when(
  `username` %in% OFTeam ~ "Office",
  `username` %in% INTeam ~ "Industrial"
))

现在我已经在我的 Raw Shift 上完成了“as_tibble”,它不会出错,也不会工作。这是不了解 Tibble 访问方法(“”、[]、.、[[]])的情况。是否值得担心或只是做一个黑客工作并使用数据框进行转换,然后再转换为小标题?我已经研究了 Tibbles 相对于数据框的好处,在我看来,使用 Tibbles 会更好,但似乎无法让它发挥作用。曾尝试使用“$”、“.” 到目前为止,在 %in% 之前没有运气。感谢您的任何建议/帮助。

标签: rdplyrtibble

解决方案


我们可能需要加载tibble

library(dplyr)
library(tibble)
head(iris) %>% 
   as_tibble %>% 
   mutate(new = case_when(Species == "setosa" ~ "hello"))
# A tibble: 6 x 6
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species new  
#         <dbl>       <dbl>        <dbl>       <dbl> <fct>   <chr>
#1          5.1         3.5          1.4         0.2 setosa  hello
#2          4.9         3            1.4         0.2 setosa  hello
#3          4.7         3.2          1.3         0.2 setosa  hello
#4          4.6         3.1          1.5         0.2 setosa  hello
#5          5           3.6          1.4         0.2 setosa  hello
#6          5.4         3.9          1.7         0.4 setosa  hello

推荐阅读