才能将2值列中的值更改为相反值

才能将2值列中的值更改为相反值

本文介绍了仅当满足另一列中的条件时,才能将2值列中的值更改为相反值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一些必须在数据框中更改的字符串的问题。我的df的结构如下:

I am having problems with some strings I have to change in my data frame. My df is structured like this:

df <- data.frame(Name = c("a2b", "a1a", "b2a", "a2b", "b1b", "b2a"),
                 Side = c("L", "R", "R", "L", "R", "L"))

    Name    Side
1    a2b       L
2    a1a       R
3    b2a       R
4    a2b       L
5    b1b       R
6    b2a       L

我要做的是将 Side列中的值替换为相反的值仅当名称(Name)值中包含 2时(该行的值 1保持不变)。 侧面(Side)列仅具有 R和 L作为可能的值。因此,这就是我想要得到的输出:

What I want to do is replace the value in the "Side" column with its opposite only when the "Name" value has a "2" in it (leaving the rows where the value has "1" unchanged). The "Side" column only has "R" and "L" as possible values. So this is the output that I would like to get:

    Name    Side
1    a2b       R
2    a1a       R
3    b2a       L
4    a2b       R
5    b1b       R
6    b2a       R

我尝试了许多解决方案,但是我刚开始使用R,所以我还真的不知道 if语句如何工作。有办法吗?

I tried many solutions but I am just starting to work with R so I don't really know how "if" statements work yet. Is there a way to do it?

推荐答案

我们根据'2'的出现创建索引('i1')在名称列中,使用该索引,对边进行子集化,并使用 chartr

We create an index ('i1') based on the occurence of '2' in 'Name' column, using that index, subset the 'Side' and change the values with chartr

i1 <- grep("2", df$Name)
df$Side[i1] <- chartr("LR", "RL", df$Side[i1])
df
#   Name Side
#1  a2b    R
#2  a1a    R
#3  b2a    L
#4  a2b    R
#5  b1b    R
#6  b2a    R






或另一种选择是使用级别进行分配,因为 Side列为 factor


Or another option is to assign using levels as the 'Side' column is factor

levels(df$Side[i1]) <- rev(levels(df$Side[i1]))

这篇关于仅当满足另一列中的条件时,才能将2值列中的值更改为相反值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 09:55