用R中的另一个值替换多列数据帧中的数字的出现次数 [英] Replacing occurrences of a number in multiple columns of data frame with another value in R
问题描述
ETA:顺便说一下,下面的内容是不必迭代我的整个列向量集,以防万一这是一个提议的解决方案(只是做了已知的事情)一次只能工作一次。)
ETA: the point of the below, by the way, is to not have to iterate through my entire set of column vectors, just in case that was a proposed solution (just do what is known to work once at a time).
有很多替换单个 R中的数据框的向量与其他值。
There's plenty of examples of replacing values in a single vector of a data frame in R with some other value.
- Replace a value in a data frame based on a conditional (
if
) statement in R - replace numbers in data frame column in r [duplicate]
以及如何用其他东西替换 NA
的所有值:
And also how to replace all values of NA
with something else:
- How to replace all values in a data.frame with another ( not 0) value
我正在寻找的是类似于上一个问题,但基本上是试图用另一个值替换一个值。对于多列符合条件的情况,或者只是尝试从多个列的前两个问题执行操作,我无法生成映射到我的实际数据帧的逻辑值数据帧。
What I'm looking for is analogous to the last question, but basically trying to replace one value with another. I'm having trouble generating a data frame of logical values mapped to my actual data frame for cases where multiple columns meet a criteria, or simply trying to do the actions from the first two questions on more than one column.
一个例子:
data <- data.frame(name = rep(letters[1:3], each = 3), var1 = rep(1:9), var2 = rep(3:5, each = 3))
data
name var1 var2
1 a 1 3
2 a 2 3
3 a 3 3
4 b 4 4
5 b 5 4
6 b 6 4
7 c 7 5
8 c 8 5
9 c 9 5
并且我想在 var1
和 var2 $ c中想要
4
的所有值$ c>要 10
。
我确信这是基本的,我只是没想过它恰当。我一直在尝试这样的事情:
I'm sure this is elementary and I'm just not thinking through it properly. I have been trying things like:
data[data[, 2:3] == 4, ]
这不起作用,但如果我对数据[,2]
而不是数据[,2:3]
,一切正常。似乎逻辑测试(如 is.na()
)可以处理多行/列,但数字比较效果不佳?
That doesn't work, but if I do the same with data[, 2]
instead of data[, 2:3]
, things work fine. It seems that logical test (like is.na()
) work on multiple rows/columns, but that numerical comparisons aren't playing as nicely?
感谢您的任何建议!
推荐答案
您想在整个数据框中搜索任何内容与您尝试替换的值匹配的值。与运行逻辑测试的方式相同,例如将所有缺失值替换为10 ..
you want to search through the whole data frame for any value that matches the value you're trying to replace. the same way you can run a logical test like replacing all missing values with 10..
data[ is.na( data ) ] <- 10
你也可以用10s替换所有4s。
you can also replace all 4s with 10s.
data[ data == 4 ] <- 10
至少我认为这就是你所追求的?
at least i think that's what you're after?
让我们说你想忽略第一行(因为它是所有字母)
and let's say you wanted to ignore the first row (since it's all letters)
# identify which columns contain the values you might want to replace
data[ , 2:3 ]
# subset it with extended bracketing..
data[ , 2:3 ][ data[ , 2:3 ] == 4 ]
# ..those were the values you're going to replace
# now overwrite 'em with tens
data[ , 2:3 ][ data[ , 2:3 ] == 4 ] <- 10
# look at the final data
data
这篇关于用R中的另一个值替换多列数据帧中的数字的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!