【问题标题】:Excluding NA in R在 R 中排除 NA
【发布时间】:2020-07-15 11:38:12
【问题描述】:

我是 R Studio 新手,我试图排除参与者回答少于 17 个问题的所有数据。我尝试使用下面的两种变体。

data1  <- data[data$frequency.participant >= 17, ] 

data1 <-data[!(data$frequency.participant <17),]

我的问题是两者都有效,例如,他们设置了 NA 答案少于 17 个的行。但除了显示 NA 之外,我还希望删除这些行。我做错了什么?

Here is an example of what my dataset looked like before running the code. There's some NAs but also answers below 17.

Here is an example of after running the code. Now everything below 17 has been replaced with NA.

【问题讨论】:

  • 那是那些命令应该做的,你确定吗?您能否在您的数据上使用dput() 发布一些示例数据并将输出粘贴到问题中。

标签: r dataframe rstudio


【解决方案1】:

原因是您的 frequency.participant 列中有 NA 值,无法使用 for ex 进行评估。 NA

data$frequency.participant[is.na(data$frequency.participant)]=0

或者

data1  <- data[data$frequency.participant >= 17 & !is.na(data$frequency.participant), ] 

【讨论】:

  • 我试过你的代码,现在我想知道我的观察次数。当我运行我的原始代码时,我的数据集从 2555 到 2450 个观察值。当我运行你的代码时,它是 2555 到 1960。数字会发生如此大的变化似乎很奇怪。
  • @Franzine 因为您之前没有删除 NA 行!试试这个sum(is.na(data$frequency.participant)),看看你的列中有多少缺失数据。
【解决方案2】:

不知道您的数据是什么样的,这个答案是暂定的: 假设您有这样的数据:

set.seed(1)
df <- data.frame(
  frequency.participant = c(NA, 11, 22, 33, 44),
  other = rnorm(5)
)

df
  frequency.participant      other
1                    NA -0.8204684
2                    11  0.4874291
3                    22  0.7383247
4                    33  0.5757814
5                    44 -0.3053884

如果您想排除数据框中 frequency.participant 值 NA 标记的所有 ,您可以这样做:

df[!df$frequency.participant < 17 & !is.na(df$frequency.participant), ] 
  frequency.participant      other
3                    22  0.7383247
4                    33  0.5757814
5                    44 -0.3053884

【讨论】:

  • 在使用您的代码时,我得到“矩阵上的下标数不正确”。
  • 谢谢!你的第二个代码正是我想要的,但我有同样的问题......它仍然显示 NA 行。
猜你喜欢
  • 2012-09-27
  • 2019-10-26
  • 1970-01-01
  • 1970-01-01
  • 2021-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-19
相关资源
最近更新 更多