【发布时间】:2020-08-01 03:11:16
【问题描述】:
我正在尝试使用索引替换大型数据框的多个列。到目前为止,我想要/已经完成的工作结合了 this post 和 this post。为了清楚起见,让我举个例子。
这里是 dput 格式的简化样本数据:
DF <-
structure(list(Fruits = structure(c(1L, 3L, 4L, 2L),
.Label = c("Apples", "Avocado", "Oranges", "Pineapple"),
class = "factor"), Weight2 = c(20L, 15L, 40L, 60L),
Weight = c(2L, 4L, 8L, 5L), `Number` = c(10L,
16L, 6L, 20L)), class = "data.frame", row.names = c(NA, -4L))
Fruits Weight Weight2 Number
Apples 20 2 10
Oranges 15 4 16
Pineapple 40 8 6
Avocado 60 5 20
我想要对 DF 做的是,给定一个水果列表,将列 Weight 和 Weight2 更改为 N。我会提到我的 DF 实际上是一个数据框列表,我的列表是一个列表列表,所以需要索引。到目前为止,这是我的代码:
fruit.to.change <- c("Apples","Pineapple")
DF$Weight[which(DF$Fruits == fruit.to.change)] <- "N" #change the first column but I want to change multiple columns.
colID <- grepl("Weight", names(DF))
which(DF$Fruits %in% fruit.to.change[1:length(fruit.to.change)]) #gets the positions matching
但不确定如何选择和替换colID 中的列?我确定这只是另一个级别的索引,但无法弄清楚。我基本上想要DF$Weight:Weight2 [which(DF$Fruits %in% fruit.to.change )] <- "N"之类的东西
非常感谢。
【问题讨论】:
标签: r dataframe indexing replace multiple-columns