【问题标题】:Copy a subset of a column, based on conditions, to another dataframe in R根据条件将列的子集复制到 R 中的另一个数据框
【发布时间】:2021-02-20 18:48:44
【问题描述】:

我的 R 技能非常有限,在寻找解决方案数小时后,我找不到可行的选项。 我有几个大型数据表。从每一个中,我想将一列的一部分复制到一个数据框中,以在那里填充一列。 我的数据表(tabn1、tabn2、tabn3)都具有相同的格式,但长度不同。每个子集将具有不同数量的行。我希望空白处用 NA 填充。我连第一列都复制不了,接下来就是下一个问题了!

Ro  Co  Red Green   Yellow
1   3   123 999 265
1   3   223 875 5877
1   4   21488   555 478
1   4   558 23698   5558
2   3   558 559 148
2   3   4579    557 59
2   4   1489    545 2369
2   4   123 999 265
3   3   558 559 148
3   3   558 23698   5558
3   4   4579    557 59
3   4   1478 4579   557
4   3   1488    555 478
4   3   1478    2945    5889
4   4   448 259 4548
4   4   26576   158 15

我的新数据框列名称:

cls <- c("n1","n2","n3")

我用列名创建了一个数据框:

df <- setNames(data.frame(matrix(ncol=3)),cls)

对于我的每个表,我只想对 Ro > = 3、Co = 3、列“Red”进行子集化 我试过了:

sub1 <- (filter(tabn1, tabn1$Ro >=3 | tabn$Co == 3)
df$n1 <- sub1$Red

> Error in `$<-.data.frame`(`*tmp*`, n1, value = c(183.94, 180.884,  : 
  replacement has 32292 rows, data has 1

还有:

df$n1 <- cut(sub1$Red)

> Error in cut.default(sub1$Red) : 
  argument "breaks" is missing, with no default

我尝试使用 df 作为数据表而不是数据框,但也出现以下错误:

df <- setNames(data.table(matrix(ncol=3)),cls)
df$n1 <- sub1$Red
> Error in set(x, j = name, value = value) : 
  Supplied 32292 items to be assigned to 1 items of column 'nn1'. If you wish to 'recycle' the RHS please use rep() to make this intent clear to readers of your code.

我随后会尝试将子集从 tabn2 复制到 df$n2,等等。如上所述,原始表格具有不同的长度。 提前致谢!

【问题讨论】:

  • 您用 1 行创建了 'df',然后为过滤后的数据分配了多行

标签: r dataframe datatable


【解决方案1】:

问题是“df”和“sub1”中的行数不同。 'df' 是用 1 行创建的。相反,我们可以直接从“sub1”本身创建“df”

df <- sub1['Red']
names(df) <- cls[1]

另外,创建 data.frame 的另一种方法是同时指定 nrow

df <- as.data.frame(matrix(nrow = nrow(sub1), ncol = length(cls)),
       dimnames = list(NULL, cls))

关于cut 的第二个错误,它需要breaks。要么我们指定休息次数

cut(sub1$Red, breaks = 3)

或断点向量

cut(sub1$Red, breaks = c(-Inf, 100, 500, 1000, Inf))

如果有很多“tabn”对象,将它们放入list,用lapply循环list

lst1 <- mget(ls(pattern = '^tabn\\d+$'))
out_lst <- lapply(lst1, function(x) subset(x, Ro >=3 | Co == 3)$Red)

subsetting 并选择“红色”列后,元素的数量可能会有所不同。如果 lengths 不同,则可以选择在末尾填充 NA,以便在 cbind 之前填充元素数量较少的人

mx <- max(lengths(out_lst))
df <- do.call(cbind, lapply(out_lst, `length<-`, mx))

【讨论】:

  • 请看我上面的编辑。原始数据表有不同的长度。当我在做多个子集时,我不知道每个表中每个子集的长度将能够先验地定义行数。谢谢
  • @ChrisDias 您可以将所有数据集放入 list 中,就像在更新的解决方案中一样
  • 但是从out_lst 如何将每个$Red 放入数据框中的单独列中?
  • @ChrisDias 如果数据集的行数与子集不同,那么最好存储为 list,因为单个 data.frame 需要具有相同的行数
  • @ChrisDias 我更新了解决方案。请检查
猜你喜欢
  • 1970-01-01
  • 2018-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-25
  • 2014-10-20
  • 2016-08-07
  • 2013-06-14
相关资源
最近更新 更多