简体   繁体   English

在 R 中查找和替换某些值

[英]Seek and replace certain values in R

I know that this has been asked thousand times already but the answers don't work for me.我知道这已经被问过一千次了,但答案对我不起作用。

I have a big dataset and need R to automatically seek and replace certain values in certain columns for me.我有一个大数据集,需要 R 为我自动查找和替换某些列中的某些值。

I tried this:我试过这个:

df$column <- replace (df$column, df$column, old number==new number)

for me it would look like this:对我来说,它看起来像这样:

df$qual_a_a_s1m1a <- replace(df$qual_a_a_s1m1a, df$qual_a_a_s1m1a, 2==3)

If I get this to work, I could then build this for all columns and all values.如果我让它工作,我可以为所有列和所有值构建它。

Can you explain why it doesn't work?你能解释为什么它不起作用吗? Thanks and have a nice sunday:)谢谢,祝你有个愉快的星期天:)

EDIT: This is one of the results I get:编辑:这是我得到的结果之一:

replace(df$qual_a_a_s1m1a, df$qual_a_a_s1m1a, 6==1)

  [1]  0  0 NA  6 NA  0 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA  2 NA
 [32] NA NA NA NA  1 NA NA NA NA NA NA NA NA  6 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
 [63] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
 [94] NA NA NA NA NA NA NA NA  6 NA NA NA NA NA NA

Instead of replacing the sixes with ones it put two zeroes in there at the first two positions.它没有用 1 替换 6,而是在前两个位置放了两个零。

Hi I think you have the syntax in the wrong format.... should it not be df$qual_a_a_s1m1a <- replace(df$qual_a_a_s1m1a, df$qual_a_a_s1m1a=3, 2)嗨,我认为您的语法格式错误....不应该是df$qual_a_a_s1m1a <- replace(df$qual_a_a_s1m1a, df$qual_a_a_s1m1a=3, 2)

also maybe you could use ifelse?也许你也可以使用 ifelse? not sure if it is faster or not but it is what I use a lot.不确定它是否更快,但这是我经常使用的。 Cheers干杯

The syntax for replace is in the wrong format.替换的语法格式错误。 See ?replace Your x is correct, but the list should be a list of your row numbers that you want to replace.请参阅?replace您的 x 是正确的,但该列表应该是您要替换的行号列表。 Then vaules would be a list of the values you want the rows in list to be converted to.然后 vaules 将是您希望将列表中的行转换为的值的列表。

This code will work a lot better than using replace():这段代码将比使用 replace() 更好地工作:

# create fake data
df <- data.frame(qual_a_a_s1m1a=rep(1:3,times=3))
df

# let's change all the 2s to 3s
df$qual_a_a_s1m1a[df$qual_a_a_s1m1a==2] <- 3

df # all the 2s are now 3s

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

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