【问题标题】:replace column value of nth column with a list of dataframes where value matches criteria用值匹配条件的数据框列表替换第 n 列的列值
【发布时间】:2017-04-19 11:18:04
【问题描述】:

如果我有以下数据框列表:

d1 <- data.frame(y1=c(1,2,3), y2=c(4,5,6))
d2 <- data.frame(y1=c(3,2,1), y2=c(6,5,4))
d3 <- data.frame(y1=c(6,5,4), y2=c(3,2,1))
d4 <- data.frame(y1=c(9,9,9), y2=c(8,8,8))

my.list <- list(d1, d2, d3, d4)

my.list
[[1]]
  y1 y2
1  1  4
2  2  5
3  3  6

[[2]]
  y1 y2
1  3  6
2  2  5
3  1  4

[[3]]
  y1 y2
1  6  3
2  5  2
3  4  1

[[4]]
  y1 y2
1  9  8
2  9  8
3  9  8

如何将第二列中大于 5 的值替换为“大于 5”,即

my.list
[[1]]
  y1 y2
1  1  4
2  2  5
3  3  'greater than five'

[[2]]
  y1 y2
1  3  'greater than five'
2  2  5
3  1  4

[[3]]
  y1 y2
1  6  3
2  5  2
3  4  1

[[4]]
  y1 y2
1  9  'greater than five'
2  9  'greater than five'
3  9  'greater than five'

我知道我可以通过以下方式测试此类情况:

sapply(sapply(my.list, "[[", 2), function(x) x > 5)
 [1] FALSE FALSE  TRUE  TRUE FALSE FALSE FALSE FALSE FALSE  TRUE  TRUE  TRUE

但无法弄清楚当测试为真时如何替换原始值。

任何帮助都会非常感谢

【问题讨论】:

    标签: r list dataframe sapply


    【解决方案1】:

    您可以在基础 R 中选择 replace

    col <- 2
    lapply(my.list, function(x) 
          data.frame(cbind(x[,-col], replace(x[,col], x[,col]>5, "greater than five"))))
    

    【讨论】:

      【解决方案2】:

      我们可以使用transformlapply

      lapply(my.list, transform, y2 = replace(y2, y2>5, "greater than 5"))
      #[1]]
      #  y1             y2
      #1  1              4
      #2  2              5
      #3  3 greater than 5
      
      #[[2]]
      #  y1             y2
      #1  3 greater than 5
      #2  2              5
      #3  1              4
      
      #[[3]]
      #  y1 y2
      #1  6  3
      #2  5  2
      #3  4  1
      
      #[[4]]
      #  y1             y2
      #1  9 greater than 5
      #2  9 greater than 5
      #3  9 greater than 5
      

      tidyverse

      library(tidyverse)
      my.list %>%
          map(~mutate(., y2 = replace(y2, y2 >5, "greater than 5")))
      

      【讨论】:

        猜你喜欢
        • 2018-09-08
        • 2018-01-01
        • 1970-01-01
        • 2018-02-11
        • 1970-01-01
        • 2022-07-06
        • 1970-01-01
        • 1970-01-01
        • 2017-07-19
        相关资源
        最近更新 更多