简体   繁体   English

如何将列中的特定值(如7)更改为R中的NA?

[英]How do you change specific values (like 7) in a column to NA in R?

我正在做一个项目,在我的专栏中,那些不知道的记录为7,而拒绝回答的记录为9。我试图找到一种简便的方法将所有这些值转换为NA。

You can use simple logic to assign NA, as in the following very simple example. 您可以使用简单的逻辑来分配NA,如以下非常简单的示例所示。

column <- c(1,2,1,3,7,7,1,2,9)
column[column %in% c(7,9)] <- NA

> column
[1]  1  2  1  3 NA NA  1  2 NA

Basically, you can operate on any column of a data frame using the $ operator. 基本上,您可以使用$运算符在数据框的任何列上进行操作。 This treats the column as a vector. 这会将列视为向量。 Using a logical operator on the vector returns a vector of TRUE or FALSE back, which can then be used to select the elements of the vector to change to NA. 在向量上使用逻辑运算符将返回TRUE或FALSE的向量,然后可以使用它们选择向量的元素以更改为NA。

I would caution that you might not always want to do that. 我警告您,您可能并不总是想要这样做。 Using NA instead of values in R can have annoying side effects because any operation against NA generally returns NA. 使用NA代替R中的值可能会带来恼人的副作用,因为针对NA的任何操作通常都会返回NA。

EDITED TO ADD: Per Gregor , I should mention that a data frame allows you to select single columns out of it using the $ operator. 编辑添加:Per Gregor ,我应该提到一个数据框允许您使用$运算符从其中选择单个列。 For instance, in data frame df.example , if the columns are A, B, and C, then df.example$A will extract column A as a vector. 例如,在数据框df.example ,如果列是A,B和C,则df.example$A将提取列A作为向量。 In contrast, the [ operator does not create vector subsets, and is used to select multiple columns of a data frame as a smaller data frame. 相反, [运算符不创建向量子集,而是用于选择数据帧的多列作为较小的数据帧。 For instance, given our example data frame, you could select columns A and B as a different data frame using df.example[c("A","B")] . 例如,给定示例数据帧,您可以使用df.example[c("A","B")]选择A和B列作为不同的数据帧。 For more guidance, trying running help('[') in R. 有关更多指导,请尝试在R中运行help('[')

You can also use the replace() function to do this: 您还可以使用replace()函数执行此操作:

df <- data.frame(value = c(1, 3, 7, 3, 9, 9, 7, 2))
df$value <- replace(df$value, which(df$value==7 | df$value==9), NA)

Result: 结果:

> df
  value
1     1
2     3
3    NA
4     3
5    NA
6    NA
7    NA
8     2

This looks cumbersome, but I've found it convenient in situations where the which piece gets messier. 这看起来很麻烦,但是我发现在which一块变得更乱的情况下很方便。 Then you do that part on another line and just point this one at the object you created there. 然后,在另一行上执行该部分,然后将其指向您在此处创建的对象。

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

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