【发布时间】:2018-04-25 07:59:06
【问题描述】:
如何在lapply 调用中将数据框的列传递给with 函数?
这些我都试过了,还是不行!
lapply(data[ , grepl( "Measured." , names( data ) ) ], with, (. <= 5 & . >= 1) | . == 4244)
lapply(data[ , grepl( "Measured." , names( data ) ) ], function(x) with((x <= 5 & x >= 1) | x == 4244))
我正在尝试查看Measured. 列中的值是否介于1 和5 之间,此外还接受4244。
样本数据集:
data <- structure(list(ID = 1:10, Date = c(2018L, 2018L, 2018L, 2015L,
2018L, 2015L, 2015L, 2014L, 2014L, 2014L), Gender = structure(c(2L,
2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L), .Label = c("F", "M"), class = "factor"),
Measured.1 = c(1L, 7L, 1L, 6L, 6L, 2L, 5L, 4L, 2L, 6L), Measured.2 = c(9L,
2L, 4L, 5L, 2L, 3L, 6L, 3L, 7L, 7L), Measured.3 = c(9L, 4L,
35L, 3L, 4L, 2L, 2L, 1L, 3L, 4L), Measured.4 = c(12L, 8L,
50L, 7L, 2L, 6L, 2L, 2L, 1L, 2L), Text = structure(c(1L,
1L, 1L, 1L, 1L, 2L, 2L, 2L, 1L, 1L), .Label = c("N", "Y"), class = "factor"),
Test = c(5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L, 6L)), .Names = c("ID",
"Date", "Gender", "Measured.1", "Measured.2", "Measured.3", "Measured.4",
"Text", "Test"), class = "data.frame", row.names = c(NA, -10L
))
及其输出:
ID Date Gender Measured.1 Measured.2 Measured.3 Measured.4 Text Test
1 1 2018 M 1 9 9 12 N 5
2 2 2018 M 7 2 4 8 N 5
3 3 2018 M 1 4 35 50 N 5
4 4 2015 M 6 5 3 7 N 5
5 5 2018 M 6 2 4 2 N 5
6 6 2015 M 2 3 2 6 Y 6
7 7 2015 F 5 6 2 2 Y 6
8 8 2014 F 4 3 1 2 Y 6
9 9 2014 F 2 7 3 1 N 6
10 10 2014 F 6 7 4 2 N 6
【问题讨论】:
-
请提供代码以制作可重现的数据
-
@griffinevo 完成。
-
对预期输出进行说明也很好(手动修改示例数据框以显示工作解决方案会产生什么) - 它使目标更加清晰
-
您在寻找
which而不是with吗? -
你的函数应该做什么?应该为您的一列数据返回什么值?
标签: r lapply with-statement