满足条件时如何添加包含特定值的列? [英] How to add a column that contains specific values when criteria is met?

查看:68
本文介绍了满足条件时如何添加包含特定值的列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框:

tibble{
x = c(1,2,3)
y = c(0,2,4)
}

我想添加一个新的变量"z",将会是:

I want to add a NEW variable "z" that will be:

z = c("Lower", "Equal", "Higher")

我当时正在考虑使用for循环,但是我不确定这是否是最有效/正确的方法.

I was thinking about using a for loop but I'm not sure if that's the most efficient/correct way.

推荐答案

在取了'x'和'y'的差后,可以用sign创建数据集中的新变量,得到sign值,使用levels和指定的相应labels将其转换为factor

The new variable in the dataset can be created with sign after taking the difference of 'x' and 'y', get the sign values, convert it to factor with levels and corresponding labels specified

library(dplyr)
df1 %>% 
 mutate(z = factor(sign(x - y), levels = c(-1, 0, 1), 
   c('Lower', "Equal", 'Higher')))


或带有case_when

df1 %>%
  mutate(tmp = x - y,
         z = case_when(tmp >0 ~ 'Higher', tmp < 0 ~ 'Lower',
             TRUE ~ 'Equal'), tmp = NULL)

数据

df1 <- tibble(
    x = c(1,2,3),
    y = c(0,2,4))

这篇关于满足条件时如何添加包含特定值的列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆