简体   繁体   English

有没有办法在 R 中使用 dplyr 根据另一个列的值创建一个新列?

[英]Is there a way to create a new column based on the values of another one using dplyr in R?

I have been using base R but I want to use dplyr .我一直在使用基础 R 但我想使用dplyr This is what I have been doing:这就是我一直在做的事情:

data$newvariable <- 0
data$newvariable[data$oldvariable=="happy"] <- "good"
data$newvariable[data$oldvariable=="unhappy"] <- "bad"
data$newvariable[data$oldvariable=="depressed"] <- "super_bad"

If oldvariable is a factor, and you don't mind newvariable being one:如果 oldvariable 是一个因素,并且您不介意 newvariable 是一个因素:

library(dplyr)

set.seed(111)
data = data.frame(
oldvariable=sample(c("happy","unhappy","depressed"),10,replace=TRUE))

data %>% mutate(newvariable=recode_factor(oldvariable,
"happy"="good","unhappy"="bad","depressed"="super_bad"))


   oldvariable newvariable
1      unhappy         bad
2    depressed   super_bad
3    depressed   super_bad
4    depressed   super_bad
5        happy        good
6    depressed   super_bad
7        happy        good
8    depressed   super_bad
9      unhappy         bad
10       happy        good

In dplyr , we can use case_when to assign new values to newvariable based on oldvariable .dplyr ,我们可以使用case_when新的值赋给newvariable基于oldvariable

library(dplyr)

data = data.frame(
  oldvariable = c("happy", "unhappy", "depressed")
)

data %>%
  mutate(newvariable = case_when(
    oldvariable == "happy" ~ "good",
    oldvariable == "unhappy" ~ "bad",
    oldvariable == "depressed" ~ "super_bad"
  ))
#>   oldvariable newvariable
#> 1       happy        good
#> 2     unhappy         bad
#> 3   depressed   super_bad

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 dplyr 根据来自另一列的值的总和创建一个新列 - Create a new column based on the sum of values from another column, with dplyr 有没有办法使用dplyr基于另一列的group_by除以创建新列? - Is there a way using dplyr to create a new column based on dividing by group_by of another column? r、dplyr:如何使用 gsub 根据另一列中的值转换一列中的值 - r, dplyr: how to transform values in one column based on value in another column using gsub 使用dplyr根据另一列中的值添加新列 - adding a new column based upon values in another column using dplyr 根据 R 中数据框中所有其他列中的字符串值,使用 dplyr 创建一个新列 - Create a new column using dplyr based on string values in all other columns in a data frame in R 如何基于一个数据框中的列的值和R中另一个数据框的列标题名称有条件地创建新列 - how to conditionally create new column based on the values of a column in one dataframe and the column header names of another dataframe in R 如何基于R中的另一列创建具有多个值的新列 - How to create a new column with multiple values based on another column in R 根据另一列(在 R 中)中的值创建一个新列 - Create a new column based on the values in another column (in R) R dplyr-根据特定值在另一列中的位置从一列中选择值 - R dplyr - select values from one column based on position of a specific value in another column 有没有办法根据另一列在一个列中创建和插入新行 - Is there a way to create and insert new rows in one column based on another column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM