根据条件(`if`)语句替换数据框中的值 [英] Replace a value in a data frame based on a conditional (`if`) statement

查看:31
本文介绍了根据条件(`if`)语句替换数据框中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面编码的R数据帧中,我想替换B的所有时间与 b 一起出现.

In the R data frame coded for below, I would like to replace all of the times that B appears with b.

junk <- data.frame(x <- rep(LETTERS[1:4], 3), y <- letters[1:12])
colnames(junk) <- c("nm", "val")

这提供:

   nm val
1   A   a
2   B   b
3   C   c
4   D   d
5   A   e
6   B   f
7   C   g
8   D   h
9   A   i
10  B   j
11  C   k
12  D   l

我最初的尝试是使用 forif 语句,如下所示:

My initial attempt was to use a for and if statements like so:

for(i in junk$nm) if(i %in% "B") junk$nm <- "b"

但是我相信你可以看到,这用 b 替换了 junk$nm 的所有值.我可以理解为什么要这样做,但我似乎无法让它仅替换原始值为 B 的垃圾 $nm 的情况.

but as I am sure you can see, this replaces ALL of the values of junk$nm with b. I can see why this is doing this but I can't seem to get it to replace only those cases of junk$nm where the original value was B.

注意:我设法用 gsub 解决了这个问题,但为了学习 R,我仍然想知道如何让我原来的方法工作(如果可能的话)

NOTE: I managed to solve the problem with gsub but in the interest of learning R I still would like to know how to get my original approach to work (if it is possible)

推荐答案

更容易将 nm 转换为字符然后进行更改:

Easier to convert nm to characters and then make the change:

junk$nm <- as.character(junk$nm)
junk$nm[junk$nm == "B"] <- "b"

如果确实需要将 nm 作为因素保留,请在最后添加:

And if indeed you need to maintain nm as factors, add this in the end:

junk$nm <- as.factor(junk$nm)

这篇关于根据条件(`if`)语句替换数据框中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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