【问题标题】:Subsetting data frame based on columns基于列子集数据框
【发布时间】:2016-09-25 19:18:36
【问题描述】:

我想根据一列中的值从数据中删除某些行。我尝试了几种方法:

#reads in data
sbc016formants.df <- read.table("file path", sep="\t", header = F, strip.white = T)

# names columns
names(sbc016formants.df) <- c("fileName", "start", "end", "vowelLabel")

# list of values I want to remove
list16 <- c(615.162, 775.885)

# produces a subset of data - removes rows with values from list 16 in the start column
sbc016formants.df <- subset(sbc016formants.df, !start %in% list16)

这会为我的一些(但不是所有)数据文件产生此错误消息:

Error in match(x, table, nomatch = 0L) : 
'match' requires vector arguments

我也试过这个,基于this主题中的第二个答案

sbc002formants.df <- sbc002formants.df[ apply(sbc002formants.df, 1 , function(x) any(unlist(x) %in% list2) ) , ]

这消除了列表中的一些项目 (list16),但不是全部。我想使用第一个答案,但我不明白代码(在示例中我不确定bl 是什么)。

这是制作可重现示例的代码:

# creates dataframe
fileName <- c("sbc016", "sbc016", "sbc016", "sbc016")
start <- c(1.345, 2.345, 615.162, 775.885)
end <- c(100.345, 200.345, 715.162, 875.885)
sbc016formants.df <- data.frame(fileName, start, end)

# list of what I want to get rid of
list16 <- c(615.162, 775.885)

【问题讨论】:

  • 试试sbc016formants.df[!(sbc016formants.df$start %in% list16),]?
  • 我试图重现错误,但没有收到错误消息
  • @aichao,这不会产生任何错误消息,但它也不会进行子集化。
  • @aichaos 评论 确实 子设置,它适用您的示例数据
  • 嗯,在您的可重现示例中对我有用。另外,我同意@Pieter 的观点,即您的subset 命令(等效)不会在您的可重现示例中产生错误。因此,我们不得不得出结论,您的数据与您的可重现示例不同。

标签: r subset


【解决方案1】:

假设我正确理解了这个问题,dplyr 应该能够轻松有效地做到这一点。

fileName <- c("sbc016", "sbc016", "sbc016", "sbc016")
start <- c(1.345, 2.345, 615.162, 775.885)
end <- c(100.345, 200.345, 715.162, 875.885)
sbc016formants.df <- data.frame(fileName, start, end)

# list of what I want to get rid of
list16 <- c(615.162, 775.885)

install.packages("dplyr", dependencies = TRUE)
library(dplyr)
sbc016formants.df %>% filter(!start %in% list16)

sbc016formants.df %>% filter(start != list16)

【讨论】:

  • 这确实有效,尽管我仍然不确定为什么以前的解决方案会失败。谢谢!
猜你喜欢
  • 1970-01-01
  • 2021-04-25
  • 2015-08-09
  • 2014-03-07
  • 1970-01-01
  • 1970-01-01
  • 2020-11-21
  • 2020-07-13
  • 2017-10-08
相关资源
最近更新 更多