Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 用值与条件匹配的数据帧列表替换第n列的列值_R_List_Dataframe_Sapply - Fatal编程技术网

R 用值与条件匹配的数据帧列表替换第n列的列值

R 用值与条件匹配的数据帧列表替换第n列的列值,r,list,dataframe,sapply,R,List,Dataframe,Sapply,如果我有以下数据帧列表: 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]]

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

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
我知道我可以通过以下方法测试此类情况:

sapply(sapply(my.list, "[[", 2), function(x) x > 5)
 [1] FALSE FALSE  TRUE  TRUE FALSE FALSE FALSE FALSE FALSE  TRUE  TRUE  TRUE
但当测试为真时,无法计算出如何替换原始值

任何帮助都将非常感谢

您可以在base R中进行替换:

col <- 2
lapply(my.list, function(x) 
      data.frame(cbind(x[,-col], replace(x[,col], x[,col]>5, "greater than five"))))
我们可以将变换与lappy结合使用

还是用提花呢

col <- 2
lapply(my.list, function(x) 
      data.frame(cbind(x[,-col], replace(x[,col], x[,col]>5, "greater than five"))))
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
library(tidyverse)
my.list %>%
    map(~mutate(., y2 = replace(y2, y2 >5, "greater than 5")))