用r中的索引替换数据帧的多列

问题描述 投票:1回答:1

我正在尝试使用索引替换大型数据框的多列。到目前为止,我要/已完成的操作将this postthis 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。是必需的。到目前为止,这是我的代码:

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
1个回答
0
投票

您可以使用:

DF[DF$Fruits %in% fruit.to.change, c("Weight", "Weight2")] <- NA
© www.soinside.com 2019 - 2024. All rights reserved.