简体   繁体   English

R | 根据另一列中的条件更改列中的元素

[英]R | Changing element in a column based on a condition in another column

This might be a basic question so apologies beforehand.这可能是一个基本问题,因此请提前道歉。 I have a database with following columns我有一个包含以下列的数据库

Name   Subject   Marks   Check
Mark   English   45      P
Susan  English   23      F
Gerald Math      33      P

I want to add 10 to value in column 'Marks' if Check == 'F'.如果 Check == 'F',我想将 10 添加到 'Marks' 列中的值。 There are many such rows so I don't want to apply a for loop有很多这样的行,所以我不想应用 for 循环

In base R , we can use a simple arithmetic approach to updatebase R ,我们可以使用简单的算术方法来更新

df$Marks <- with(df, (Check == 'F') * 10 + Marks)

Or create a logical condition in base R and do the assignment或者在base R创建一个逻辑条件并进行赋值

i1 <- df$Check == 'F'
df$Marks[i1] <- df$Marks[i1] + 10

-output -输出

df
#    Name Subject Marks Check
#1   Mark English    45     P
#2  Susan English    33     F
#3 Gerald    Math    33     P

Or in data.table way, the assignment operation is more simple as the general syntax of data.table is [i, j, by] where i can be integer index or logical condition.或者在data.table方式中,赋值操作更简单,因为data.table的一般语法是[i, j, by] ,其中i可以是整数索引或逻辑条件。 Here, we specify the logical condition ( Check == 'F' ), specify the j ( Marks + 10 ) and assign ( := ) it to the same column.在这里,我们指定逻辑条件( Check == 'F' ),指定jMarks + 10 )并将其分配( := )到同一列。 The original data.frame is converted to data.table with setDT原来的data.tablesetDT转换成setDT

library(data.table)
setDT(df)[Check == 'F', Marks := Marks + 10]

The evaluation happens from left to right ie first it converts to data.table ( setDT ), evaluates the i , do the assignment on the expression ( Marks + 10 ) on the 'Marks' column评估从左到右进行,即首先转换为 data.table ( setDT ),评估i ,对“Marks”列上的表达式 ( Marks + 10 ) 进行赋值


Or with dplyr或者用dplyr

library(dplyr)
df %>%
      mutate(Marks = case_when(Check == 'F' ~ Marks + 10L, TRUE ~ Marks))

data数据

df <- structure(list(Name = c("Mark", "Susan", "Gerald"), Subject = c("English", 
"English", "Math"), Marks = c(45L, 23L, 33L), Check = c("P", 
"F", "P")), class = "data.frame", row.names = c(NA, -3L))

You can also use ifelse() :您还可以使用ifelse()

#Base R sol
df$Marks <- ifelse(df$Check=='F',df$Marks+10,df$Marks)

Output:输出:

    Name Subject Marks Check
1   Mark English    45     P
2  Susan English    33     F
3 Gerald    Math    33     P

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM