简体   繁体   English

用另一个值将列中的值替换为数据框(对所有值都相同)

[英]replace values in a column into Data Frame with another value (same for all)

My data frame consists of 21 columns, for this problem only one is relevant: I want replace values 2 or 3 or 4 or 5 in a column a with the value 1 (in the same column).我的数据框由 21 列组成,对于这个问题只有一列是相关的:我想将 a 列中值 2 或 3 或 4 或 5 替换为值 1(在同一列中)。

beside of doing the code below for any value 2,3,4,5 i'm looking for something more elegant:除了为任何值 2、3、4、5 执行下面的代码之外,我正在寻找更优雅的东西:

  df <- df %>% mutate (a = replace(a, a == 2,1))
  df <- df %>% mutate (a = replace(a, a == 3,1))
  df <- df %>% mutate (a = replace(a, a == 4,1))
  df <- df %>% mutate (a = replace(a, a == 5,1))

so i'm just stock with the condition "or" i need create inside the code... any solution?所以我只知道条件“或”我需要在代码中创建...任何解决方案?

You can replace multiple columns using across and multiple values with %in% .您可以使用across和多个值替换多个列%in% For example, if you want to replace values from column a , b , c and d , you can do:例如,如果要替换列abcd中的值,您可以执行以下操作:

library(dplyr)
df <- df %>% mutate(across(a:d, ~replace(., . %in% 2:5, 1)))
#For dplyr < 1.0.0 use `mutate_at`
#df <- df %>% mutate_at(vars(a:d), ~replace(., . %in% 2:5, 1))

In base R, you can do this with lapply :在基数 R 中,您可以使用lapply执行此操作:

cols <- c('a','b','c','d')
df[cols] <- lapply(df[cols], function(x) replace(x, x %in% 2:5, 1))

暂无
暂无

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

相关问题 如何用另一个值替换数据框中的值 - How to replace values in a data frame with another value r - 将data.frame列中的值替换为基于同一列的唯一ID中的不同值 - r - Replace values in a data.frame column with a different value in the same column based unique ID 将数据框中的值替换为同一 dataframe 中另一列的对应值 - Replace value in data frame with corresponding value from another column in same dataframe 如何对共享另一列中给出的相同ID的所有行在数据框中标准化列值? - How can I normalize column values in a data frame for all rows that share the same ID given in another column? 如何用之前同一列中的值替换数据框列中的0值,所以(n-1) - How to replace 0 values in data frame columns by the value in the same column before, so (n-1) 删除某些列值与另一列不匹配的行(全部在同一数据框中) - Removing certain rows whose column value does not match another column (all within the same data frame) 根据匹配的列名将数据框每一列中的所有值乘以另一个值 - Multiply all values in each column of a data frame by another value based on matching column names R根据另一个数据框的精确匹配替换列的值 - R replace values of a column based on exact match of another data frame 匹配另一列中的模式后替换数据框列中的值 - Replace values in columns of a data frame after match a pattern in another column 当数据框的几列中的值在另一个特定列中具有相同的值时,如何更改它们? - How to change the values in several columns of a data frame, when they have the same value in another specific column?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM