有条件地将字符串转换为特定的数值 [英] Conditionally convert strings to a specific numeric value

查看:70
本文介绍了有条件地将字符串转换为特定的数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我敢肯定有一个简单的答案,但是我已经扫描了堆栈溢出并且没有找到解决方案.似乎将sapply和ifelse函数结合起来可以完成这项工作(但我不确定).

I'm sure there is an easy answer for this , but I have scanned stack overflow and haven't been able to find a solution. It would seem that potentially a combination of sapply and ifelse functions would do the job (but I'm not sure).

所以我有一个带有字符的数据框,除了一列是数字值之外.

So I have a dataframe with characters, except one column which is a numeric value.

####Create dataframe which needs converting
df <- data.frame(Sample_1 = rep(letters[1:3], each = 3),
             Sample_2 = rep("a", times = 9))
df$Number <- rep(seq(from=1,to=3,by=1))

我想将此数据框中的字符转换为特定数字.字符需要转换为何种字符取决于最后一列中的数字.因此标准是:

I would like to convert the characters in this dataframe to a specific number. What the character needs to be converted to depends on the number in the final column. So the criteria would be:

  • 如果Number = 1,则a应更改为30,b应更改为20,c应更改为10
  • 如果Number = 2,则a应该更改为35,b应该更改为25,c应该更改为15
  • 如果Number = 3,则a应该更改为40,b应该更改为30,c应该更改为20

以下是突出显示此转化的数据框

Here is a dataframe highlighting this conversion

A <- c(30,20,10)
B <- c(35,25,15)
C <- c(40,30,20)
Conversion_df <- data.frame(A, B,C)

这是所需的输出.

Final <- data.frame(Sample_1 = c(30,20,10,35,25,15,40,30,20),
                Sample_2 = c(30,20,10,30,20,10,30,20,10))

在此先感谢您的帮助.

Thank you in advance for any help.

推荐答案

首先,我们可以使用if语句创建一个函数来评估样本:

First we can create a function to valuate the sample with if's statements:

valuate_sample <- function(x,y) {
    ifelse(y==1, ifelse(x=='a',30, ifelse(x=='b',20, 10)),
           ifelse(y==2, ifelse(x=='a',35, ifelse(x=='b',25, 15)),
                  ifelse(y==3, ifelse(x=='a',40, ifelse(x=='b',30, 20)),0)))
}

在我们只需要在您的数据框中使用该函数之后:

After we just need to use the function in your dataframe:

df <- df %>% 
    mutate(
        Sample_1 = valuate_sample(Sample_1, Number),
        Sample_2 = valuate_sample(Sample_2, Number)
        )

结果:

这篇关于有条件地将字符串转换为特定的数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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