更新R data.frame中的单个值(不是行) [英] Updating individual values (not rows) in an R data.frame
问题描述
我想根据一个简单的标准更新R data.frame mydata
中的 var3
值。
I would like to update values of var3
in an R data.frame mydata
according to a simple criterion.
var1 var2 var3
1 1 4 5
2 3 58 800
3 8 232 8
我认为应该执行以下操作:
I would think that the following should do:
mydata$var3[mydata$var3 > 500,] <- NA
但是,这会将每个匹配记录的整行替换为NA(行中的所有单元格),而不仅仅是 var3
值(单元格):
However, this replaces the entire row of every matching record with NA (all cells of the row), instead of just the var3
value (cell):
var1 var2 var3
1 1 4 5
2 NA NA NA
3 8 232 8
如何确保仅替换所选变量的值? mydata
应该看起来像这样
How can I ensure that just the value for the selected variable is replaced? mydata
should then look like
var1 var2 var3
1 1 4 5
2 3 58 NA
3 8 232 8
推荐答案
使用 which
和 arr.ind = TRUE
> mydata[which(mydata[,3]>500, arr.ind=TRUE), 3] <- NA
> mydata
var1 var2 var3
1 1 4 5
2 3 58 NA
3 8 232 8
或者只是修改您以前的尝试...
Or just modify your previous attempt...
mydata[mydata$var3 > 500, 3] <- NA
这也有效
mydata$var3[mydata$var3 > 500 ] <- NA # note no comma is inside [ ]
中没有逗号,因为 mydata $ var3
给出一个向量,您正在使用 [mydata $ var3> 500,]
,因此会引发尺寸错误。差不多了,您所要做的就是删除代码中的逗号(请参阅我的最后一个选择)。
Your attempt didnt work because mydata$var3
gives a vector and you are indexing it as if it were a matrix by using [mydata$var3 > 500,]
so a dimension error is thrown. You almost got it, all you have to do is remove the comma in your code (see my last alternative).
这篇关于更新R data.frame中的单个值(不是行)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!