如何使用dplyr有效地将数字列分成组?

时间:2019-10-23 07:14:14

标签: r dplyr

我有一个数字列,并尝试使用case_when函数。我知道ntile()可以将数字分成相等的组,例如

# data
data = data.frame(id=c(1,1,1,2,2,2,3,3,3,4,4,4), time=seq(1:3), x=seq(from=10, to=120, by=10))

# automatic grouping works
data%>%
  mutate(x_group = ntile(x, n=4))

但是我想手动指定这些组:

# manual grouping fails 
data %>%
  mutate(x_group = case_when(x < 30 ~ 1,
                               30 <= x < 50 ~ 2,
                               50 <= x < 70 ~ 3,
                               70 <= x ~ 4))

我想问题可能出在条件组合中?

1 个答案:

答案 0 :(得分:2)

您必须在R中指定两个单独的逻辑比较

import React from "react";
import Menu from "@material-ui/core/Menu";
import MenuItem from "@material-ui/core/MenuItem";
import { makeStyles } from "@material-ui/core/styles";

function App() {
  const useStyles = makeStyles({
    custom: {
      borderColor: "green",
      borderWidth: "2px",
      borderStyle: "solid"
    },
    list: {
      backgroundColor: "yellow"
    }
  });

  const classes = useStyles();

  return (
    <Menu
      id="simple-menu"
      open={true}
      classes={{
        paper: classes.custom,
        list: classes.list
      }}
    >
      <MenuItem>Item 1</MenuItem>
      <MenuItem>Item 2</MenuItem>
      <MenuItem>Item 3</MenuItem>
    </Menu>
  );
}

export default App;