我有一个包含多个列(可以是动态列数)的data.table
,我希望对其应用最小值.每列都有自己的特定最小值.
我的data.table
的基本版本是这样的:
library(data.table)
dt <- data.table(
urn = 1:10,
col1 = 5:14,
col2 = 11:20
)
Note: I've only included two columns with values that need to have minimums for the reprex. There could be more columns, hence trying to code this a little bit dynamically.个
我的方法是嵌套lapply
个语句等等,但是我不知道如何在lapply
个函数中调用我的列.
min_vals <- c(10, 15)
my_cols <- grep("^col", colnames(dt), value = TRUE)
## First approach
dt[,
(my_cols) := lapply(min_vals, function(x) {
my_cols[my_cols < x] <- x
})]
## Second Approach
dt[,
(my_cols) := lapply(min_vals, function(x) {
ifelse(my_cols < x, x, my_cols)
})]
目前,第一种方法将所有行设置为相应的min_vals
,而不仅仅是低于min_vals
的值.第二种方法根本不起作用,反而会出错.
所需的输出如下所示:
dt
# urn col1 col2
# <int> <int> <int>
# 1: 1 10 15
# 2: 2 10 15
# 3: 3 10 15
# 4: 4 10 15
# 5: 5 10 15
# 6: 6 10 16
# 7: 7 11 17
# 8: 8 12 18
# 9: 9 13 19
# 10: 10 14 20
如果有一种解决方案允许动态编号与col<number>
格式匹配的列,那就太好了.