Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何用R中的NA替换特定行和列中的某些值?_R_Dplyr - Fatal编程技术网

如何用R中的NA替换特定行和列中的某些值?

如何用R中的NA替换特定行和列中的某些值?,r,dplyr,R,Dplyr,在我的数据框中,我想用NA替换某些空白单元格和值单元格。但我想用NAs替换的单元格与单元格存储的值无关,而是与它存储的行和列的组合有关 下面是一个示例数据帧DF: Fruits Price Weight Number of pieces Apples 20 2 10 Oranges 15 4 16 Pineapple 40 8 6 Avocado

在我的数据框中,我想用NA替换某些空白单元格和值单元格。但我想用NAs替换的单元格与单元格存储的值无关,而是与它存储的行和列的组合有关

下面是一个示例数据帧DF:

  Fruits   Price   Weight   Number of pieces

  Apples      20      2          10
  Oranges     15      4          16
  Pineapple   40      8           6
  Avocado     60      5          20
我想把菠萝的重量换成NA,把橙子的件数换成NA

DF$Weight[3] <- NA
DF$`Number of pieces`[2] <- NA  
但若表格的顺序改变,这将用NA替换错误的值


我应该怎么做呢?

因为数据结构是二维的,所以可以先找到包含特定值的行的索引,然后使用这些信息

which(DF$Fruits == "Pineapple")
[1]  3
DF$Weight[which(DF$Fruits == "Pineapple")] <- NA
which(DF$Fruits==“菠萝”)
[1]  3
DF$重量[其中(DF$水果==“菠萝”)]
结果:由于读取数据,碎片数被截断为数字

     Fruits Price Weight Number
1    Apples    20      2     10
2   Oranges    15      4     NA
3 Pineapple    40     NA      6
4   Avocado    60      5     20

下面是一种使用函数
is.n的方法。您打算替换多少行?我的数据集中有37行26列。我打算用NA替换不同行/列组合中的至少10个单元格。
library(dplyr)
df %>% 
  mutate(Weight=ifelse(Fruits=="Pineapple",NA,Weight),
         Number=ifelse(Fruits=="Oranges",NA,Number))#use Number of Pieces
     Fruits Price Weight Number
1    Apples    20      2     10
2   Oranges    15      4     NA
3 Pineapple    40     NA      6
4   Avocado    60      5     20
is.na(DF$Weight) <- DF$Fruits == "Pineapple"
is.na(DF$`Number of pieces`) <- DF$Fruits == "Oranges"

DF
#     Fruits Price Weight Number of pieces
#1    Apples    20      2               10
#2   Oranges    15      4               NA
#3 Pineapple    40     NA                6
#4   Avocado    60      5               20
DF <-
structure(list(Fruits = structure(c(1L, 3L, 4L, 2L), 
.Label = c("Apples", "Avocado", "Oranges", "Pineapple"), 
class = "factor"), Price = c(20L, 15L, 40L, 60L), 
Weight = c(2L, 4L, 8L, 5L), `Number of pieces` = c(10L, 
16L, 6L, 20L)), class = "data.frame", row.names = c(NA, -4L))