Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
644 views
in Technique[技术] by (71.8m points)

dplyr - How to replace certain values in a specific rows and columns with NA in R?

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.

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

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.

Output:

 Fruits   Price   Weight   Number of pieces

  Apples      20      2          10
  Oranges     15      4          NA
  Pineapple   40      NA           6
  Avocado     60      5          20

But if order of the table is changed, this would replace wrong values with NA.

How should I do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since your data structure is 2 dimensional, you can find the indices of the rows containing a specific value first and then use this information.

which(DF$Fruits == "Pineapple")
[1]  3
DF$Weight[which(DF$Fruits == "Pineapple")] <- NA

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...