【问题标题】:replace multiple columns of data frame with indexing in r用r中的索引替换多列数据框
【发布时间】:2020-08-01 03:11:16
【问题描述】:

我正在尝试使用索引替换大型数据框的多个列。到目前为止,我想要/已经完成的工作结合了 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。我会提到我的 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 )] &lt;- "N"之类的东西 非常感谢。

【问题讨论】:

    标签: r dataframe indexing replace multiple-columns


    【解决方案1】:

    我们可以使用fruit.to.change 对行进行子集,使用colID 对列进行子集化,并将满足条件的位置替换为"N"

    DF[DF$Fruits %in% fruit.to.change,colID] <- "N"
    DF
    #     Fruits Weight2 Weight Number
    #1    Apples       N      N     10
    #2   Oranges      15      4     16
    #3 Pineapple       N      N      6
    #4   Avocado      60      5     20
    

    【讨论】:

    • 非常感谢!我什至没有想过像那样使用向量 colID。
    【解决方案2】:

    dplyr 的选项是

    library(dplyr)
    DF %>%
       mutate_at(vars(colID), ~ replace(., Fruits %in% fruit.to.change,  "NA"))
    

    【讨论】:

      猜你喜欢
      • 2017-12-26
      • 2013-12-28
      • 2018-01-31
      • 2014-11-04
      • 2022-08-18
      • 2023-02-14
      • 2020-10-23
      • 2017-07-23
      • 1970-01-01
      相关资源
      最近更新 更多