如何用R中的NA替换特定行和列中的某些值?
在我的数据框中,我想用NA替换某些空白单元格和具有值的单元格.但是我要替换为NA的单元格与单元格存储的值无关,而是与行和列的组合存储在其中.
In my data frame, I want to replace certain blank cells and cells with values with NA. But the cells I want to replace with NAs has nothing to do with the value that cell stores, but with the combination of row and column it is stored in.
这是一个示例数据帧DF:
Here's a sample data frame DF:
Fruits Price Weight Number of pieces
Apples 20 2 10
Oranges 15 4 16
Pineapple 40 8 6
Avocado 60 5 20
我想将Pineapple'e的重量替换为NA,将Orange的件数替换为NA.
I want to replace Pineapple'e weight to NA and Orange's number of pieces to NA.
DF$Weight[3] <- NA
DF$`Number of pieces`[2] <- NA
这将替换存储在该位置中并且可能会更改的任何值.我想使用特定的行和列名称进行此替换,因此值的位置变得无关紧要.
This replaces any value that's stored in that position and that may change. I want to use specific row and column names to do this replacement so the position of value becomes irrelevant.
输出:
Fruits Price Weight Number of pieces
Apples 20 2 10
Oranges 15 4 NA
Pineapple 40 NA 6
Avocado 60 5 20
但是,如果更改表的顺序,这将用NA替换错误的值.
But if order of the table is changed, this would replace wrong values with NA.
我应该怎么做?
由于您的数据结构是2维的,因此可以先找到包含特定值的行的索引,然后使用此信息.
Since you data structure is 2 dimensional you can find the indices of the rows containing a specific value first and use this information.
which(DF$Fruits == "Pineapple")
[1] 3
DF$Weight[which(DF$Fruits == "Pineapple")] <- NA
您应该知道哪个
将返回向量,因此,如果您有多个称为"Pineapple"的水果,则上一条命令将返回它们的所有索引.
You should be aware of that which
will return a vector, so if you have multiple fruits called "Pineapple" then the previous command will return all indices of them.